Knowledgebase (2705)
Children categories
Autofit Text and Shapes in PowerPoint with JavaScript in React
2026-11-17 01:56:58 Written by liu taliaWhen building slides, the amount of text rarely matches the size of its shape: a paragraph that is a little too long spills past the border, while a short caption leaves a large empty area. Fixing this by hand — reducing font sizes or dragging shape edges page by page — is slow and hard to keep consistent across a deck. Autofit rules let the text and the shape accommodate each other automatically, so later content changes do not require another round of layout work.
This article uses Spire.Presentation for JavaScript to control the relative size of text and shapes through the AutofitType property of a TextFrame, which offers three modes: keep the shape size, shrink the text, or resize the shape. The whole process runs locally in the browser through WebAssembly, requires no Office installation and no back-end service, and keeps the presentation from leaving the user's device.
This article covers two features:
For installation and project configuration, see Integrating Spire.Presentation for JavaScript in a React Project. The examples below assume that Spire.Presentation for JavaScript is installed and the WebAssembly module has been initialized.
Shrink overflowing text to fit the shape
When text runs past the edge of its shape, the extra lines sit outside the border and break the layout; reducing the font size by hand, on the other hand, may shrink other text that was already fine. Setting the TextFrame autofit mode to shrink text on overflow keeps the shape at its original size and only scales down the text that does not fit, so the content still lands inside the original outline.
| Usage | Result |
|---|---|
slide.Shapes.get_Item(index) |
Gets a shape on the slide by index, starting from 0 |
shape.TextFrame.AutofitType = TextAutofitType.Normal |
Shrinks the text when it overflows, keeping the shape size unchanged |
The steps are:
- Get the Spire.Presentation WASM module and make sure it is ready, then load the font file and the presentation into the VFS.
- Create a
Presentationobject, load the presentation withLoadFromFile(), and get the first slide withSlides.get_Item(0). - Get the shape whose text overflows its border with
Shapes.get_Item(index). - Set the shape's
TextFrame.AutofitTypetoTextAutofitType.Normalso the overflowing text shrinks to fit the shape. - Save the presentation with
SaveToFile(), release it withPresentation.Dispose(), then read the file from the VFS and trigger the download.
The code for shrinking overflowing text to fit the shape is as follows:
function App() {
const shrinkTextOnOverflow = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font and the presentation into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'PresentationFit.pptx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the presentation and get the first slide
const ppt = new pptModule.Presentation();
ppt.LoadFromFile(inputFileName);
const slide = ppt.Slides.get_Item(0);
// Take the rectangle whose text overflows and shrink the text to fit the shape
const shape = slide.Shapes.get_Item(0);
shape.TextFrame.AutofitType = pptModule.TextAutofitType.Normal;
// Save the presentation
const outputFileName = 'ShrinkText_result.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the result file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Shrink Text</h1>
<button onClick={shrinkTextOnOverflow}>
Start
</button>
</div>
);
}
export default App;
Presentation after shrinking overflowing text to fit the shape:

Resize a shape to fit its text
A shape that is much taller or wider than its text leaves a large blank area on the slide and makes neighboring elements hard to align. Setting the autofit mode to resize the shape to fit its text keeps the font size unchanged and recalculates the shape from the amount of text, so the outline hugs the content and the layout becomes more compact.
| Usage | Result |
|---|---|
slide.Shapes.get_Item(index) |
Gets a shape on the slide by index |
shape.TextFrame.AutofitType = TextAutofitType.Shape |
Resizes the shape to fit its text, keeping the font size unchanged |
The steps are:
- Get the Spire.Presentation WASM module and make sure it is ready, then load the font file and the presentation into the VFS.
- Create a
Presentationobject, load the presentation withLoadFromFile(), and get the first slide withSlides.get_Item(0). - Get the shape that is much taller than its text with
Shapes.get_Item(index). - Set the shape's
TextFrame.AutofitTypetoTextAutofitType.Shapeso the shape shrinks to fit the content. - Save the presentation with
SaveToFile(), release it withPresentation.Dispose(), then read the file from the VFS and trigger the download.
The code for resizing a shape to fit its text is as follows:
function App() {
const resizeShapeToFitText = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font and the presentation into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'PresentationFit.pptx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the presentation and get the first slide
const ppt = new pptModule.Presentation();
ppt.LoadFromFile(inputFileName);
const slide = ppt.Slides.get_Item(0);
// Take the tall rounded rectangle and shrink the shape to fit its text
const shape = slide.Shapes.get_Item(1);
shape.TextFrame.AutofitType = pptModule.TextAutofitType.Shape;
// Save the presentation
const outputFileName = 'FitShape_result.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the result file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Fit Shape</h1>
<button onClick={resizeShapeToFitText}>
Start
</button>
</div>
);
}
export default App;
Presentation after resizing a shape to fit its text:

FAQ
How do I turn autofit off and restore the original text size
Cause: After text has been shrunk, it is displayed at the reduced size; to restore it, the autofit mode has to be set back to no autofit.
Solution: Set the shape's AutofitType to TextAutofitType.None:
shape.TextFrame.AutofitType = pptModule.TextAutofitType.None;
The saved presentation then carries no autofit rule, so the text keeps its original font size and overflows the shape when it is too long.
What is the difference between the three autofit modes
Cause: TextAutofitType decides which side stays unchanged — the text or the shape — and has three values.
Solution: Choose one according to the layout:
TextAutofitType.None: both the shape size and the font size stay unchanged, and text that does not fit keeps overflowing.TextAutofitType.Normal: the shape size stays unchanged, and the text is scaled down when it does not fit.TextAutofitType.Shape: the font size stays unchanged, and the shape is recalculated from the amount of text.
Get a Free License
If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.
Add Text Boxes to PowerPoint Slides with JavaScript in React
2026-11-17 01:56:45 Written by liu taliaTitles, explanations and key points on a slide are mostly presented as text. Inserting a text box and adjusting its formatting page by page takes time and is hard to keep consistent across batch-generated documents; writing the text directly into fixed layout placeholders also limits control over position and style. Creating text boxes through code lets you write the text and control the layout while the presentation is generated, so the content and its appearance stay stable and reusable.
This article uses Spire.Presentation for JavaScript to add text boxes to PowerPoint slides in the browser. The whole process runs locally on the user's device through WebAssembly, requires no Office installation and no back-end service, and keeps the presentation from leaving the browser.
This article covers two core features:
For installation and project configuration, see Integrating Spire.Presentation for JavaScript in a React Project. The examples below assume that Spire.Presentation for JavaScript is installed and the WebAssembly module has been initialized.
Add a Text Box to a PowerPoint Slide
A text box carries a piece of text that stands on its own, can be placed anywhere on the page, and is not tied to the placeholders of a layout. When adding a text box, define its position and size first and then write the text, so the content lands exactly where it is expected; removing the default fill and outline leaves only the text visible.
| Usage | Result |
|---|---|
slide.Shapes.AppendShape({ shapeType, rectangle }) |
Add a rectangle inside the given area to serve as a text box |
RectangleF.FromLTRB(left, top, right, bottom) |
Define the position and size of the text box with its top-left and bottom-right coordinates |
shape.Fill.FillType = FillFormatType.None |
Remove the fill of the text box |
shape.Line.FillType = FillFormatType.None |
Remove the outline of the text box |
shape.AppendTextFrame(text) |
Write a piece of text into the text box |
shape.TextFrame.TextRange |
Get the text in the text box to set its size and color |
shape.TextFrame.Paragraphs.get_Item(index).Alignment |
Set the horizontal alignment of a paragraph inside the text box |
The steps are:
- Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, and create a
Presentationobject. - Get the first slide with
Presentation.Slides.get_Item(0). - Add a
ShapeType.Rectangleshape withShapes.AppendShape(), and define its position and size withRectangleF.FromLTRB(). - Set
Fill.FillTypeandLine.FillTypetoFillFormatType.Noneto remove the fill and the outline of the text box. - Call
shape.AppendTextFrame()to write the text, then set the font size and the text color throughTextFrame.TextRange, and center the paragraph. - Call
Presentation.SaveToFile()to save the result file andDispose()to release the presentation, then read the file from the VFS and trigger the download.
The code for adding a text box to a PowerPoint slide is as follows:
function App() {
const addTextBox = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Create a presentation and get the first slide
const ppt = new pptModule.Presentation();
const slide = ppt.Slides.get_Item(0);
// Add a rectangle shape to serve as a text box
const shape = slide.Shapes.AppendShape({
shapeType: pptModule.ShapeType.Rectangle,
rectangle: pptModule.RectangleF.FromLTRB(60, 180, 660, 360),
});
// Remove the fill and the outline, leaving only the text
shape.Fill.FillType = pptModule.FillFormatType.None;
shape.Line.FillType = pptModule.FillFormatType.None;
// Write text into the text box
shape.AppendTextFrame('Quarterly Business Review');
// Set the font size and the text color
const textRange = shape.TextFrame.TextRange;
textRange.FontHeight = 40;
textRange.Fill.FillType = pptModule.FillFormatType.Solid;
textRange.Fill.SolidColor.Color = pptModule.Color.get_Black();
shape.TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Center;
// Save the result file
const outputFileName = 'AddTextBox_result.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add a Text Box</h1>
<button onClick={addTextBox}>
Add a text box
</button>
</div>
);
}
export default App;
Presentation after adding a text box to a blank slide:

Style a Text Box with Fill, Border, Shadow and Rotation
A newly added text box is only an area for text and often looks plain on a designed page. Giving it a gradient fill, a border and an outer shadow, and rotating it slightly, turns it into a distinct block of information that stands apart from the background and other elements; the text color is adjusted as well so it stays legible on the darker fill.
| Usage | Result |
|---|---|
shape.Fill.FillType = FillFormatType.Gradient |
Set the fill of the text box to a gradient |
shape.Fill.Gradient.GradientShape = GradientShapeType.Linear |
Set the gradient type to linear |
shape.Fill.Gradient.GradientStops.Append({ position, color }) |
Add color stops to the gradient and determine its direction and colors |
shape.Line.FillType = FillFormatType.Solid |
Set the border of the text box to a solid line |
shape.Line.Width = n |
Set the width of the border |
shape.Line.SolidFillColor.Color = Color.get_xxx() |
Set the border color |
new OuterShadowEffect() |
Create an outer shadow effect object |
shadowEffect.BlurRadius, shadowEffect.Direction, shadowEffect.Distance |
Set the blur radius, direction and distance of the shadow |
shadowEffect.ColorFormat.Color = Color.get_xxx() |
Set the shadow color |
shape.EffectDag.OuterShadowEffect = shadowEffect |
Apply the outer shadow to the text box |
shape.Rotation = n |
Rotate the text box by an angle |
textRange.FontHeight = n |
Set the font size of the text in the text box |
textRange.Fill.SolidColor.Color = Color.get_xxx() |
Set the text color |
The steps are:
- Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, create a
Presentationobject and get the first slide. - Add a rectangle text box with
Shapes.AppendShape(), and write two lines of text withshape.AppendTextFrame(). - Through
TextFrame.TextRange, set the text to white at 30 points, specify the fonts withLatinFontandEastAsianFont, and center each paragraph. - Set
Line.FillTypetoFillFormatType.Solid, and useLine.WidthandLine.SolidFillColor.Colorto give the text box a white border. - Set
Fill.FillTypetoFillFormatType.Gradient, specify a linear gradient withGradientShape, and add the light blue and cadet blue stops withGradientStops.Append(). - Create an
OuterShadowEffect, setBlurRadius,Direction,DistanceandColorFormat.Color, and assign it toEffectDag.OuterShadowEffect. - Rotate the text box 5 degrees clockwise with
Rotation, then save the result file, release the presentation and read the file from the VFS to trigger the download.
The code for styling the text box is as follows:
function App() {
const styleTextBox = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font file into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
// Create a presentation and get the first slide
const ppt = new pptModule.Presentation();
const slide = ppt.Slides.get_Item(0);
// Add a rectangle text box
const shape = slide.Shapes.AppendShape({
shapeType: pptModule.ShapeType.Rectangle,
rectangle: pptModule.RectangleF.FromLTRB(80, 150, 630, 370),
});
// Write two lines of text and set them to white, 30 points
shape.AppendTextFrame('Hello, world!\nQuarterly Business Review');
const textRange = shape.TextFrame.TextRange;
textRange.Fill.FillType = pptModule.FillFormatType.Solid;
textRange.Fill.SolidColor.Color = pptModule.Color.get_White();
textRange.FontHeight = 30;
textRange.LatinFont = new pptModule.TextFont('Arial');
textRange.EastAsianFont = new pptModule.TextFont('Arial');
for (let i = 0; i < shape.TextFrame.Paragraphs.Count; i++) {
shape.TextFrame.Paragraphs.get_Item(i).Alignment = pptModule.TextAlignmentType.Center;
}
// Give the text box a white solid outline
shape.Line.FillType = pptModule.FillFormatType.Solid;
shape.Line.Width = 2.5;
shape.Line.SolidFillColor.Color = pptModule.Color.get_White();
// Fill the text box with a linear gradient from light sky blue to cadet blue
shape.Fill.FillType = pptModule.FillFormatType.Gradient;
shape.Fill.Gradient.GradientShape = pptModule.GradientShapeType.Linear;
shape.Fill.Gradient.GradientStops.Append({ position: 0, color: pptModule.Color.get_LightSkyBlue() });
shape.Fill.Gradient.GradientStops.Append({ position: 1, color: pptModule.Color.get_CadetBlue() });
// Add an outer shadow
const shadowEffect = new pptModule.OuterShadowEffect();
shadowEffect.BlurRadius = 20;
shadowEffect.Direction = 30;
shadowEffect.Distance = 8;
shadowEffect.ColorFormat.Color = pptModule.Color.get_LightGray();
shape.EffectDag.OuterShadowEffect = shadowEffect;
// Rotate the text box 5 degrees clockwise
shape.Rotation = 5;
// Save the result file
const outputFileName = 'StyleTextBox_result.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Style the Text Box</h1>
<button onClick={styleTextBox}>
Style the text box
</button>
</div>
);
}
export default App;
Presentation after styling a text box with a gradient fill, border, shadow and rotation:

FAQ
How to keep long text from wrapping
Cause: A text box wraps at its boundary by default, and a long sentence split into several lines can disrupt the layout.
Solution: Set WordWrap to false so the text stays on one line and runs beyond the text box:
shape.TextFrame.WordWrap = false;
How to set vertical text in a text box
Cause: Text is arranged horizontally by default, so a vertical title or side label needs an explicit direction.
Solution: Set VerticalTextType to VerticalTextType.Vertical to turn the text into a vertical layout; use VerticalTextType.EastAsianVertical if CJK characters should stay upright:
shape.TextFrame.VerticalTextType = pptModule.VerticalTextType.Vertical;
How to adjust the distance between text and the text box border
Cause: Text sits close to the edge by default and can look cramped when there is a lot of text or a thick border.
Solution: Set the four inner margin properties to control the distance:
shape.TextFrame.MarginLeft = 60;
shape.TextFrame.MarginTop = 40;
shape.TextFrame.MarginRight = 20;
shape.TextFrame.MarginBottom = 10;
How to remove a text box from a slide
Cause: A text box is an item in the shape collection of the slide; changing its text does not remove the text box itself.
Solution: Get the text box object and remove it with Remove() on the shape collection:
const shape = slide.Shapes.get_Item(0);
slide.Shapes.Remove(shape);
Get a Free License
If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.
Create SmartArt Graphics in PowerPoint with JavaScript in React
2026-11-13 09:46:49 Written by liu taliaWhen a process, hierarchy, or cycle is written as a list of sentences, readers have to compare line after line to work out the order and the relationships. A SmartArt graphic arranges the nodes according to a layout and draws the connections directly, and it re-flows as nodes are added to it. Drawing the same diagram by hand in PowerPoint is slow and makes consistent spacing and alignment hard to keep.
This article uses Spire.Presentation for JavaScript to create and adjust SmartArt graphics in PowerPoint in the browser. The whole process runs locally on the user's device through WebAssembly, requires no Office installation and no back-end service, and the presentation never leaves the browser.
The article covers two features:
For installation and project configuration, see Integrating Spire.Presentation for JavaScript in a React Project. The examples below assume that Spire.Presentation for JavaScript is installed and the WebAssembly module has been initialized.
Create SmartArt Graphics in PowerPoint
To create SmartArt graphics in PowerPoint, start by choosing a layout that matches the relationship in the content, then write the text into the nodes. The layout decides how the nodes are arranged and where the connectors run; it is specified once at creation, and only the node text needs to be maintained afterwards. Once inserted, the graphic can still be moved and resized like any other shape.
| What you write | What you get |
|---|---|
slide.Shapes.AppendSmartArt(x, y, width, height, layoutType) |
Adds a SmartArt graphic of the given layout at the specified position and size |
smartArt.Nodes.Count |
The number of nodes currently in the graphic |
smartArt.Nodes.RemoveNode({ index: i }) |
Removes the node at index i |
smartArt.Nodes.AddNode() |
Appends a node to the end of the node collection |
node.TextFrame.Text |
Sets or reads the text of a node |
The steps are:
- Get the Spire.Presentation WASM module, make sure it is ready, and load the font file and the presentation into the VFS.
- Create a
Presentationobject, callLoadFromFile()to load the presentation, and useSlides.get_Item()to get the slide that will hold the graphic. - Call
Shapes.AppendSmartArt()with the position, size, and aSmartArtLayoutTypeto get theISmartArtobject. - Walk from
Nodes.Countdownwards and callNodes.RemoveNode()to remove the placeholder nodes that come with the layout. - Call
Nodes.AddNode()in order and write the text throughTextFrame.Text. - Call
Presentation.SaveToFile()to save the result, release the presentation withDispose(), then read the file from the VFS and trigger the download.
The code for creating SmartArt graphics in PowerPoint is shown below:
function App() {
const createSmartArt = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font and the presentation into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SmartArt.pptx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the presentation and get the first slide
const ppt = new pptModule.Presentation();
ppt.LoadFromFile(inputFileName);
const slide = ppt.Slides.get_Item(0);
// Add a process-layout SmartArt at the specified position and size
const smartArt = slide.Shapes.AppendSmartArt(50, 160, 620, 200, pptModule.SmartArtLayoutType.BasicProcess);
// Remove the placeholder nodes that come with the layout
for (let i = smartArt.Nodes.Count - 1; i >= 0; i--) {
smartArt.Nodes.RemoveNode({ index: i });
}
// Add the nodes in process order and write their text
const steps = ['Requirements', 'Design', 'Development', 'Launch'];
for (const text of steps) {
const node = smartArt.Nodes.AddNode();
node.TextFrame.Text = text;
}
// Save the result file
const outputFileName = 'CreateSmartArt.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Create SmartArt Graphics</h1>
<button onClick={createSmartArt}>
Create SmartArt
</button>
</div>
);
}
export default App;
Presentation after creating a SmartArt graphic in PowerPoint:

Add Nodes to a SmartArt Graphic
When you add nodes to a SmartArt graphic, you can build the hierarchy level by level: add a top-level node first, then add subordinate nodes to its child node collection, or insert one at a given position so the new node lands in the right order. The text and reporting relations of the existing nodes stay as they are, and the graphic re-flows around the new node count.
| What you write | What you get |
|---|---|
smartArt.Nodes.AddNode() |
Adds a node at the top level of the graphic |
node.ChildNodes.AddNode() |
Appends a child node under the specified node |
node.ChildNodes.AddNodeByPosition(position) |
Inserts a child node at the specified position under the node and shifts the following children back |
node.TextFrame.Text |
Sets the text of the new node |
The steps are:
- Get the Spire.Presentation WASM module, make sure it is ready, and load the font file and the presentation into the VFS.
- Create a
Presentationobject, callLoadFromFile()to load the presentation, useSlides.get_Item()to get the slide, and add an organization-chart SmartArt withShapes.AppendSmartArt(). - Iterate the node collection backwards and clear the placeholder nodes that come with the layout with
Nodes.RemoveNode(). - Call
Nodes.AddNode()to add the top-level node and write its text withTextFrame.Text. - Add departments under the top-level node with
ChildNodes.AddNode(), then insert one at a given position withChildNodes.AddNodeByPosition(). - Call
AddNode()on a department'sChildNodesto add the next level. - Call
Presentation.SaveToFile()to save the result, release the presentation withDispose(), then read the file from the VFS and trigger the download.
The code for adding nodes to a SmartArt graphic is shown below:
function App() {
const addNodes = async () => {
// Get the Spire.Presentation WASM module
const pptModule = window.wasmModule?.spirepresentation;
// Check that the module is ready
if (!pptModule) {
alert('Spire.Presentation is not ready yet');
return;
}
// Load the font and the presentation into the VFS
await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
const inputFileName = 'SmartArt.pptx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);
// Load the presentation and get the first slide
const ppt = new pptModule.Presentation();
ppt.LoadFromFile(inputFileName);
const slide = ppt.Slides.get_Item(0);
// Add an organization-chart SmartArt and clear its placeholder nodes
const smartArt = slide.Shapes.AppendSmartArt(50, 160, 620, 200, pptModule.SmartArtLayoutType.OrganizationChart);
for (let i = smartArt.Nodes.Count - 1; i >= 0; i--) {
smartArt.Nodes.RemoveNode({ index: i });
}
// Top-level node
const root = smartArt.Nodes.AddNode();
root.TextFrame.Text = 'Headquarters';
// Add departments under the top-level node
const dev = root.ChildNodes.AddNode();
dev.TextFrame.Text = 'Engineering';
const mkt = root.ChildNodes.AddNode();
mkt.TextFrame.Text = 'Marketing';
// Insert a department at a given position
const ops = root.ChildNodes.AddNodeByPosition(1);
ops.TextFrame.Text = 'Operations';
// Add a team under the engineering department
const team = dev.ChildNodes.AddNode();
team.TextFrame.Text = 'Frontend Team';
// Save the result file
const outputFileName = 'AddSmartArtNodes.pptx';
ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], { type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add SmartArt Nodes</h1>
<button onClick={addNodes}>
Add Nodes
</button>
</div>
);
}
export default App;
Presentation after adding nodes to the SmartArt graphic:

FAQ
What is the difference between Nodes and ChildNodes
Cause: Nodes returns the nodes at every level of the graphic, while ChildNodes returns only the direct children of one node. The two collections serve different purposes.
Solution: Use Nodes to walk the whole graphic, and a node's ChildNodes to read, add, or remove its direct children:
// Every node in the graphic
for (let i = 0; i < smartArt.Nodes.Count; i++) {
console.log(smartArt.Nodes.get_Item(i).TextFrame.Text);
}
// The direct children of one node
const root = smartArt.Nodes.get_Item(0);
for (let i = 0; i < root.ChildNodes.Count; i++) {
console.log(root.ChildNodes.get_Item(i).TextFrame.Text);
}
Why does a node added as a child end up at the top level
Cause: smartArt.Nodes.AddNode() adds a node at the top level of the graphic instead of under the current node. On an organization chart the new node becomes another top-level node and stays at level 0.
Solution: To add a node as a subordinate, call ChildNodes.AddNode() on that node; to insert it at a position, use ChildNodes.AddNodeByPosition():
const root = smartArt.Nodes.get_Item(0);
const child = root.ChildNodes.AddNode();
child.TextFrame.Text = 'New node';
Get a Free License
If you wish to delete the evaluation message from the resulting documents, or to get rid of function limitations, please contact sales to obtain a valid 30-day temporary license.