Image and Shapes

Image and Shapes (16)

Once a presentation is finalized and distributed, the diagrams, title backgrounds and badges on its slides are easily dragged or resized by mistake, and the text may drift away from the original design. Adding restrictions to the shapes keeps these elements in place; when taking over an existing presentation or reusing someone else's layout, it is also necessary to find out which shapes are already restricted before deciding what to adjust. Checking them one by one by hand is slow and easy to miss on individual shapes.

This article uses Spire.Presentation for JavaScript to perform these operations 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.


Lock the Layout of Shapes

The position and size of a finished layout are the result of repeated adjustments, and any offset spoils the overall look. Restricting a shape item by item pins its position, size, type and aspect ratio, forbids rewriting the text inside it and dragging its adjustment handles. Rotation and selection stay enabled, so the angle or the layout can still be fine-tuned while working.

Code Result
Presentation.LoadFromFile(fileName) Load the presentation from the VFS
slide.Shapes.get_Item(i) Get the shape at the given index
shape.Locking.PositionProtection Set to true to forbid moving the shape
shape.Locking.ResizeProtection Set to true to forbid resizing the shape
shape.Locking.ShapeTypeProtection Set to true to forbid changing the shape type
shape.Locking.AspectRatioProtection Set to true to forbid changing the aspect ratio
shape.Locking.RotationProtection Set to false to keep rotating the shape
shape.Locking.SelectionProtection Set to false to keep selecting the shape
shape.Locking.TextEditingProtection Set to true to forbid editing the text
shape.Locking.AdjustHandlesProtection Set to true to forbid dragging the adjustment handles

The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the presentation into the VFS, then open it with Presentation.LoadFromFile() and take its first slide.
  2. Walk slide.Shapes and take each shape with get_Item(i).
  3. Set PositionProtection, ResizeProtection, ShapeTypeProtection, AspectRatioProtection, TextEditingProtection and AdjustHandlesProtection under Locking to true to restrict moving, size, type, aspect ratio, text editing and the adjustment handles.
  4. Set RotationProtection and SelectionProtection to false to keep rotation and selection available.
  5. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and start the download.

The following code shows how to lock the layout of shapes:

function App() {
  const preventShapeChanges = 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 presentation into the VFS
    const inputFileName = 'en_Shapes.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the presentation and take its first slide
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);
    const slide = ppt.Slides.get_Item(0);

    // Walk the shapes and forbid moving, resizing, editing the text and dragging the adjustment handles, keeping rotation and selection
    for (let i = 0; i < slide.Shapes.Count; i++) {
      const shape = slide.Shapes.get_Item(i);
      shape.Locking.RotationProtection = false;
      shape.Locking.SelectionProtection = false;
      shape.Locking.ResizeProtection = true;
      shape.Locking.PositionProtection = true;
      shape.Locking.ShapeTypeProtection = true;
      shape.Locking.AspectRatioProtection = true;
      shape.Locking.TextEditingProtection = true;
      shape.Locking.AdjustHandlesProtection = true;
    }

    // Save the result file
    const outputFileName = 'PreventShapeChanges.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and start 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>Prevent shape changes</h1>
      <button onClick={preventShapeChanges}>
        Prevent shape changes
      </button>
    </div>
  );
}

export default App;

The presentation after moving, resizing and text editing are forbidden:

The presentation after moving, resizing and text editing are forbidden


Read and Check the Lock Status of Shapes

When an existing presentation arrives, there is usually no way to tell which shapes have been restricted or which items were locked. Opening each shape's formatting pane is slow, and a shape whose selection is forbidden cannot even be selected. Reading the locking properties of every shape and collecting them into a text report makes the whole state visible at a glance, which helps decide what to adjust next. The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the presentation with locked shapes into the VFS, then open it with Presentation.LoadFromFile() and take its first slide.
  2. Walk slide.Shapes, take each shape with get_Item(i), and read the shape text with TextFrame.Text as its label.
  3. Read the eight properties under Locking, turn each one into "Locked" or "Allowed", and build a few lines of text per shape.
  4. Write the report to a text file in the VFS with FS.writeFile(), then release the presentation with Dispose().
  5. Read the text file from the VFS and start the download.

The code for reading and checking the lock status of shapes is shown below:

function App() {
  const readShapeLocks = 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 presentation with locked shapes into the VFS
    const inputFileName = 'en_LockedShapes.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}data/`);

    // Load the presentation and take its first slide
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);
    const slide = ppt.Slides.get_Item(0);

    // Read the locking properties of every shape and build a text report
    const state = (flag) => (flag ? 'Locked' : 'Allowed');
    const lines = ['Shape Lock Status Report', '================'];
    for (let i = 0; i < slide.Shapes.Count; i++) {
      const shape = slide.Shapes.get_Item(i);
      let text = '';
      try {
        text = shape.TextFrame.Text;
      } catch (err) {
        text = '';
      }
      const locking = shape.Locking;
      lines.push(`Shape ${i + 1}: ${text}`);
      lines.push(`  Position: ${state(locking.PositionProtection)}, Size: ${state(locking.ResizeProtection)}, Rotation: ${state(locking.RotationProtection)}, Selection: ${state(locking.SelectionProtection)}`);
      lines.push(`  Type: ${state(locking.ShapeTypeProtection)}, Aspect ratio: ${state(locking.AspectRatioProtection)}, Text editing: ${state(locking.TextEditingProtection)}, Adjust handles: ${state(locking.AdjustHandlesProtection)}`);
    }

    // Write the report to a text file in the VFS
    const outputFileName = 'ShapeLockStatus.txt';
    window.dotnetRuntime.Module.FS.writeFile(outputFileName, lines.join('\n'));
    ppt.Dispose();

    // Read the text file and start the download
    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'text/plain;charset=utf-8' });
    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>Read lock status</h1>
      <button onClick={readShapeLocks}>
        Read lock status
      </button>
    </div>
  );
}

export default App;

The text report generated by reading the lock states:

The text report generated by reading the lock states


FAQ

Can tables be locked as well

Cause: A table is another shape type in a presentation, and the way it is adjusted is similar to ordinary shapes.

Solution: Test the shape with instanceof to see whether it is a table, then use ShapeLocking to set the matching protection, for example to fix the aspect ratio:

if (shape instanceof pptModule.ITable) {
  shape.ShapeLocking.AspectRatioProtection = true;
}

How is locking different from document encryption

Cause: Both restrict what can be changed in a presentation, so they are easily confused; but locking constrains how shapes behave in an editor, and only for the shapes it was applied to.

Solution: The lock items only affect dragging, resizing, rotating and text editing in editors such as PowerPoint. They require no password and do not stop Spire.Presentation from reading or changing shape properties. To control who may open the file, use document encryption or an open password instead.

Do new shapes inherit the lock settings

Cause: The lock items are written shape by shape and are not stored in the slide master or layout, so a newly added shape does not carry them automatically.

Solution: After the shape collection changes, run the same traversal again and set the same Locking properties on the new shapes. If the new shape follows the same layout as the existing ones, reuse the same set of lock items.


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.

Cards, buttons and labels on a slide are often drawn as rounded rectangles: a softly rounded outline looks gentler than sharp corners and separates content from the page more clearly. Drawing each shape by hand and tuning the corner arc is hard to keep consistent once there are many shapes, and every color change means repeating the work.

This article uses Spire.Presentation for JavaScript to add rounded rectangles to PowerPoint presentations 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 Rounded Rectangle to a PowerPoint Slide

The rounded rectangle is one of the most common emphasis shapes, well suited to holding titles, buttons or quotes. To add one to a slide, give its position and size, then set the corner radius, and finally adjust the fill and outline so the shape lands where intended and matches the page colors.

Syntax Result
slide.Shapes.AppendShape({ shapeType, rectangle }) Adds a rounded rectangle inside the given rectangle
ShapeType.RoundCornerRectangle A rectangle whose four corners are rounded
shape.SetRoundRadius(radius) Sets the corner radius of the rounded rectangle
shape.Fill.FillType and shape.Fill.SolidColor.Color Switches the fill to a solid color and sets the fill color
shape.Line.FillType and shape.Line.SolidFillColor.Color Switches the outline to a solid line and sets the outline color

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, then create a Presentation object and get the first slide.
  2. Use Shapes.AppendShape() with ShapeType.RoundCornerRectangle and a rectangle to add a rounded rectangle.
  3. Call shape.SetRoundRadius() to set the corner radius as a proportion of the shape width.
  4. Set the fill through Fill.FillType and Fill.SolidColor.Color, and the outline through Line.FillType and Line.SolidFillColor.Color.
  5. Call Presentation.SaveToFile() to save the result, release the presentation with Dispose(), then read the file from the VFS to trigger the download.

The following code adds a rounded rectangle to a PowerPoint slide:

function App() {
  const addRoundedRectangle = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Create a presentation, which comes with a blank slide by default
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // Append a four-corner rounded rectangle within the given rectangle
    const shape = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.RoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(210, 150, 510, 330),
    });

    // Set the corner radius to one third of the width
    shape.SetRoundRadius(shape.Width / 3);

    // Set the solid fill and the outline color
    shape.Fill.FillType = pptModule.FillFormatType.Solid;
    shape.Fill.SolidColor.Color = pptModule.Color.get_LightBlue();
    shape.Line.FillType = pptModule.FillFormatType.Solid;
    shape.Line.SolidFillColor.Color = pptModule.Color.get_SkyBlue();
    shape.Line.Width = 3;

    // Save the resulting file
    const outputFileName = 'AddRoundedRectangle.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS to 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 Rounded Rectangle</h1>
      <button onClick={addRoundedRectangle}>
        Add Rounded Rectangle
      </button>
    </div>
  );
}

export default App;

The presentation after adding a rounded rectangle to a blank slide:

The presentation after adding a rounded rectangle to a blank slide


Draw Rectangles with Different Corner Combinations

Not every rounded rectangle rounds all four corners equally. Process arrows need a single rounded side, tabs often use diagonal corners, and connector blocks in diagrams tend to use two corners on one side. Spire.Presentation for JavaScript ships several corner-combination shape types; add them one by one and set a consistent radius so a group of shapes shares the same curve.

Syntax Result
ShapeType.RoundCornerRectangle All four corners rounded
ShapeType.OneRoundCornerRectangle Only one corner rounded
ShapeType.OneSnipOneRoundCornerRectangle One rounded corner and one snipped corner
ShapeType.TwoDiagonalRoundCornerRectangle Two rounded corners on a diagonal
ShapeType.TwoSamesideRoundCornerRectangle Two rounded corners on the same side
shape.SetRoundRadius(radius) Sets a consistent corner radius for each shape

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, then create a Presentation object and get the first slide.
  2. Add the five corner-combination rectangles one by one with Shapes.AppendShape().
  3. Call shape.SetRoundRadius() on each shape to set the corner radius.
  4. Give each shape a different fill and outline color so the corner styles are easy to tell apart.
  5. Call Presentation.SaveToFile() to save the result, release the presentation with Dispose(), then read the file from the VFS to trigger the download.

The following code draws rectangles with different corner combinations:

function App() {
  const addRoundedVariants = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check whether the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Create a presentation, which comes with a blank slide by default
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // Five corner-combination rectangles, each added explicitly with its own colors
    const shape1 = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.RoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(60, 90, 220, 220),
    });
    shape1.SetRoundRadius(shape1.Width / 3);
    shape1.Fill.FillType = pptModule.FillFormatType.Solid;
    shape1.Fill.SolidColor.Color = pptModule.Color.get_LightBlue();
    shape1.Line.FillType = pptModule.FillFormatType.Solid;
    shape1.Line.SolidFillColor.Color = pptModule.Color.get_SkyBlue();
    shape1.Line.Width = 2;

    // One rounded corner: light green fill, sea green outline
    const shape2 = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.OneRoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(270, 90, 430, 220),
    });
    shape2.SetRoundRadius(shape2.Width / 3);
    shape2.Fill.FillType = pptModule.FillFormatType.Solid;
    shape2.Fill.SolidColor.Color = pptModule.Color.get_LightGreen();
    shape2.Line.FillType = pptModule.FillFormatType.Solid;
    shape2.Line.SolidFillColor.Color = pptModule.Color.get_SeaGreen();
    shape2.Line.Width = 2;

    // One rounded and one snipped corner: light yellow fill, orange outline
    const shape3 = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.OneSnipOneRoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(480, 90, 640, 220),
    });
    shape3.SetRoundRadius(shape3.Width / 3);
    shape3.Fill.FillType = pptModule.FillFormatType.Solid;
    shape3.Fill.SolidColor.Color = pptModule.Color.get_LightYellow();
    shape3.Line.FillType = pptModule.FillFormatType.Solid;
    shape3.Line.SolidFillColor.Color = pptModule.Color.get_Orange();
    shape3.Line.Width = 2;

    // Two diagonal rounded corners: light pink fill, violet red outline
    const shape4 = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.TwoDiagonalRoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(60, 290, 220, 420),
    });
    shape4.SetRoundRadius(shape4.Width / 3);
    shape4.Fill.FillType = pptModule.FillFormatType.Solid;
    shape4.Fill.SolidColor.Color = pptModule.Color.get_LightPink();
    shape4.Line.FillType = pptModule.FillFormatType.Solid;
    shape4.Line.SolidFillColor.Color = pptModule.Color.get_MediumVioletRed();
    shape4.Line.Width = 2;

    // Two same-side rounded corners: light cyan fill, cadet blue outline
    const shape5 = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.TwoSamesideRoundCornerRectangle,
      rectangle: pptModule.RectangleF.FromLTRB(270, 290, 430, 420),
    });
    shape5.SetRoundRadius(shape5.Width / 3);
    shape5.Fill.FillType = pptModule.FillFormatType.Solid;
    shape5.Fill.SolidColor.Color = pptModule.Color.get_LightCyan();
    shape5.Line.FillType = pptModule.FillFormatType.Solid;
    shape5.Line.SolidFillColor.Color = pptModule.Color.get_CadetBlue();
    shape5.Line.Width = 2;

    // Save the resulting file
    const outputFileName = 'RoundedRectangleVariants.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS to 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>Rounded Rectangle Variants</h1>
      <button onClick={addRoundedVariants}>
        Draw Corner Variants
      </button>
    </div>
  );
}

export default App;

The presentation after drawing the five corner variants:

The presentation after drawing the five corner variants


Frequently Asked Questions

How to add text to a rounded rectangle and center it

Cause: Rounded rectangles often hold a title or button label; after adding the shape you need to write text and set paragraph alignment so the text sits centered horizontally within the shape.

Solution: Use AppendTextFrame() to write the text, then set the first paragraph's alignment to TextAlignmentType.Center:

shape.AppendTextFrame('Rounded rectangle text');
shape.TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Center;

How to modify a rounded rectangle in an existing presentation

Cause: When working with an existing file, the rounded rectangle usually sits among other shapes on a slide, so you need to locate it before changing it.

Solution: Open the presentation with LoadFromFile(), iterate over slide.Shapes, check shape.ShapeType for RoundCornerRectangle, then change its fill or corner radius:

const ppt = new pptModule.Presentation();
ppt.LoadFromFile('Sample.pptx');
const slide = ppt.Slides.get_Item(0);
for (let i = 0; i < slide.Shapes.Count; i++) {
  const shape = slide.Shapes.get_Item(i);
  if (shape.ShapeType === pptModule.ShapeType.RoundCornerRectangle) {
    shape.Fill.FillType = pptModule.FillFormatType.Solid;
    shape.Fill.SolidColor.Color = pptModule.Color.get_LightGreen();
    shape.SetRoundRadius(shape.Width / 4);
  }
}
ppt.SaveToFile({ file: 'Modified.pptx', fileFormat: pptModule.FileFormat.Pptx2013 });
ppt.Dispose();

How to delete a rounded rectangle from a presentation

Cause: If you remove an element while iterating by index, the index shifts forward and you can skip shapes or run past the end.

Solution: Take the shape object first, remove it with slide.Shapes.Remove(shape), and step the loop index back by one:

for (let i = 0; i < slide.Shapes.Count; i++) {
  const shape = slide.Shapes.get_Item(i);
  if (shape.ShapeType === pptModule.ShapeType.RoundCornerRectangle) {
    slide.Shapes.Remove(shape);
    i--;
  }
}

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.

By the second or third revision of a deck, the images are usually the first thing to go stale: the product has a new look and the hero shot has to be swapped whole; the layout tightens and the pictures need to shrink proportionally; a diagram is no longer needed and should come off the page. Clicking through slide after slide in desktop software repeats the same moves for dozens of pages; handing it to a server means uploading the file first.

This article adjusts, replaces and deletes PowerPoint images directly in the browser with Spire.Presentation for JavaScript. All three operations work on SlidePicture, the shape that holds a picture. The whole process runs in the browser via WebAssembly, with no Office installation and no backend dependency, and the file always stays on the user's device.

This article covers three core tasks:

For installation and project setup, see Integrate Spire.Presentation for JavaScript in a React project. The examples below assume Spire.Presentation is installed and the WebAssembly module is initialized.


Edit images in PowerPoint

Spire.Presentation for JavaScript provides the IEmbedImage interface, which can edit a picture's size, position, rotation angle, name, alternative text and transparency on a slide.

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load a PowerPoint presentation with the Presentation.LoadFromFile() method.
  3. Iterate over every slide in the document and every shape on each slide.
  4. Set the image properties.
  5. Save the result with Presentation.SaveToFile(), read it from the VFS, and trigger a browser download.

The code to edit images is as follows:

function App() {
  const editImages = 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 sample presentation and fonts
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', '', `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // Create a Presentation instance and load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile('SamplePresentation.pptx');

    // Iterate over slides and shapes
    let pictureIndex = 0;
    for (let i = 0; i < ppt.Slides.Count; i++) {
      const slide = ppt.Slides.get_Item(i);
      for (let j = 0; j < slide.Shapes.Count; j++) {
        const shape = slide.Shapes.get_Item(j);

        // Check whether it is a picture shape, then cast it to IEmbedImage
        if (shape instanceof pptModule.SlidePicture) {
          const image = pptModule.IEmbedImage.Convert(shape);

          // Set size, position and rotation
          image.Width = 200;
          image.Height = 150;
          image.Left = 80 + pictureIndex * 220;
          image.Top = 160;
          image.Rotation = 10;

          // Set name, alternative text and alternative title
          image.Name = `ProductImage_${pictureIndex + 1}`;
          image.AlternativeText = 'Product showcase image';
          image.AlternativeTitle = `image${pictureIndex + 1}`;

          // Set transparency (percentage)
          image.PictureFill.Picture.Transparency = 30;

          pictureIndex++;
        }
      }
    }

    // Save the result file
    const outputFileName = 'Edited-Images.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and trigger a 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>Edit PowerPoint Images</h1>
      <button id="btn-1" onClick={editImages}>
        Edit Images
      </button>
    </div>
  );
}

export default App;

The image size, position, rotation and transparency have all been updated:

The image size, position, rotation and transparency have all been updated


Replace a specific image in PowerPoint

Spire.Presentation for JavaScript provides the Presentation.Images collection to replace a specific picture on a slide with a new image.

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the sample presentation, the new image and fonts, create a Presentation object and load the presentation.
  3. Open the new image file with new Stream(), and add it to the image resources through Presentation.Images.Append().
  4. Get the target slide, iterate over its Shapes, find the picture by AlternativeTitle, and replace its EmbedImage.
  5. Save the result, read it from the VFS, and trigger a browser download.

The code to replace a specific image is as follows:

function App() {
  const replaceImage = 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 sample presentation, the new image and fonts
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', '', `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('NewImage.png', '', `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // Create a Presentation instance and load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile('SamplePresentation.pptx');

    // Add the new image to the document's image resources
    const stream = new pptModule.Stream('NewImage.png');
    const image = ppt.Images.Append({ stream });
    stream.Close();

    // Get the second slide and replace the picture whose alternative title is image1
    const slide = ppt.Slides.get_Item(1);
    for (let i = 0; i < slide.Shapes.Count; i++) {
      const shape = slide.Shapes.get_Item(i);
      if (shape instanceof pptModule.SlidePicture && shape.AlternativeTitle === 'image1') {
        shape.PictureFill.Picture.EmbedImage = image;
      }
    }

    // Save the result file
    const outputFileName = 'Replaced-Image.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and trigger a 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>Replace a Specific Image in PowerPoint</h1>
      <button id="btn-2" onClick={replaceImage}>
        Replace Image
      </button>
    </div>
  );
}

export default App;

The target image on the second slide has been swapped for the new one:

The target image on the second slide has been swapped for the new one

Locate the image by order

The example matches the target picture by AlternativeTitle, whose value comes from the alternative title set in the document. When a picture has no alternative title, you can locate it by its order on the page:

// Take the first picture on the second slide
const slide = ppt.Slides.get_Item(1);
let pictureIndex = 0;
for (let i = 0; i < slide.Shapes.Count; i++) {
  const shape = slide.Shapes.get_Item(i);
  if (shape instanceof pptModule.SlidePicture) {
    if (pictureIndex === 0) {
      shape.PictureFill.Picture.EmbedImage = image;
    }
    pictureIndex++;
  }
}

Delete images in PowerPoint

Spire.Presentation for JavaScript provides the Shapes.RemoveAt() method to delete picture shapes from a slide.

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the sample presentation and fonts, create a Presentation object and load the file.
  3. Get the second slide with Slides.get_Item(1).
  4. Iterate over Shapes from the end to the beginning, filter pictures with instanceof SlidePicture, and delete them with RemoveAt().
  5. Save the result, read it from the VFS, and trigger a browser download.

The code to delete images from a slide is as follows:

function App() {
  const deleteImages = 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 sample presentation and fonts
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', '', `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // Create a Presentation instance and load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile('SamplePresentation.pptx');

    // Get the second slide
    const slide = ppt.Slides.get_Item(1);

    // Iterate from the end to the beginning and delete all picture shapes on the slide
    for (let i = slide.Shapes.Count - 1; i >= 0; i--) {
      if (slide.Shapes.get_Item(i) instanceof pptModule.SlidePicture) {
        slide.Shapes.RemoveAt(i);
      }
    }

    // Save the result file
    const outputFileName = 'Deleted-Images.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and trigger a 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>Delete Images in PowerPoint</h1>
      <button id="btn-3" onClick={deleteImages}>
        Delete Images
      </button>
    </div>
  );
}

export default App;

All pictures on the second slide have been removed:

All pictures on the second slide have been removed

Delete only a specific image

When you do not want to clear the whole page, add a condition to the loop and remove only the matching picture:

// Iterate in reverse and delete only the image whose alternative title is image1
for (let i = slide.Shapes.Count - 1; i >= 0; i--) {
  const shape = slide.Shapes.get_Item(i);
  if (shape instanceof pptModule.SlidePicture && shape.AlternativeTitle === 'image1') {
    slide.Shapes.RemoveAt(i);
  }
}

FAQ

Why does the image only change from the top-left corner after resizing

Cause: Width and Height only change the size of the picture shape; Left and Top keep their original values, so the top-left corner becomes the anchor point for scaling.

Solution: To scale around the center or the page, adjust Left and Top at the same time:

// Scale around the original center
const centerX = shape.Left + shape.Width / 2;
const centerY = shape.Top + shape.Height / 2;
shape.Width = shape.Width * scale;
shape.Height = shape.Height * scale;
shape.Left = centerX - shape.Width / 2;
shape.Top = centerY - shape.Height / 2;

Why can't the target image be found when replacing

Cause: The example checks shape.AlternativeTitle === 'image1', and the target picture in the sample presentation already has this alternative title set. If the document does not set it, or the value differs, the condition never matches.

Solution: Print the alternative titles of all picture shapes on the page first, then match the actual value. You can also switch to locating the image by order, as shown above.

if (shape instanceof pptModule.SlidePicture) {
  console.log(shape.AlternativeTitle, shape.Name);
}

Why does a replaced image look stretched or blurry

Cause: Replacing only swaps the embedded image source; the picture shape's width and height do not change. When the new image's aspect ratio differs from the original frame, it is stretched. When the new image's resolution is lower than the display size, it looks soft.

Solution: Pick an image with a similar aspect ratio, or adjust Width and Height after the replacement. To preserve the ratio, compute one value from the new image's aspect ratio.

Why can images still be seen on the slide after deletion

Cause: The code only removes SlidePicture shapes from the slide's Shapes. Pictures in the master, the layout, the background fill, and inside group shapes are not in this collection.

Solution: Handle master pictures through Presentation.Masters; clear the fill of the slide to remove background pictures; ungroup group shapes first, or recurse into the group to find picture shapes.


Get a Free License

If you want to remove the evaluation message from the resulting document or lift the feature limits, contact sales for a temporary license valid for 30 days.

If all the text on a slide shows up at once, the audience has to take in every point at the same moment; revealing a block of text paragraph by paragraph makes the pace of the explanation much easier to follow. Setting the animation for each paragraph by hand takes time and is hard to keep consistent once the deck grows. Setting text animations with Spire.Presentation for JavaScript while the presentation is generated fixes how each paragraph enters, and later reuse needs no repeated adjustment.

This article uses Spire.Presentation for JavaScript to animate text 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 keeps the presentation from leaving the browser.

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.


Animate the paragraphs of the text

A block of text often falls into several paragraphs: a summary first, then the details one by one. When an animation is added to the whole text box, all the text plays as one piece; splitting the animation by paragraph lets the points appear in turn. The number of paragraphs is not fixed, so read the paragraph count first, then loop over it and add one effect per paragraph, each limited to its own range; to bring out just one paragraph first, give that paragraph its own start and end range.

Writing Result
slide.Shapes.get_Item(index) Returns a shape of the slide by index; text shapes use the same member
slide.Timeline.MainSequence.AddEffect(shape, effectType) Adds an animation effect to a shape and returns the effect object
effect.SetStartEndParagraphs(start, end) Limits the effect to the given paragraphs; paragraph indexing starts at 0
shape.TextFrame.Paragraphs.Count Returns the number of paragraphs in the text shape, used as the loop bound
AnimationEffectType.FadedZoom, etc. Selects the entrance effect, such as faded zoom

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font and the presentation into the VFS, then create a Presentation object and load the file.
  2. Get the first slide through Presentation.Slides.get_Item(0) and take its text shape with Shapes.get_Item().
  3. Read the paragraph count through TextFrame.Paragraphs.Count and use it as the number of loop iterations.
  4. Inside the loop, call MainSequence.AddEffect() on the text shape, then use SetStartEndParagraphs() to make the i-th paragraph the range of that effect.
  5. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and trigger the download.

The code for animating the paragraphs of the text is as follows:

function App() {
  const animateParagraphs = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check if the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Load the font and the presentation into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'en_AnimationText.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);

    // Get the first slide and its text shape
    const slide = ppt.Slides.get_Item(0);
    const textShape = slide.Shapes.get_Item(1);

    // Get the number of paragraphs in the text shape
    const paragraphCount = textShape.TextFrame.Paragraphs.Count;

    // Add one animation effect for each paragraph
    for (let i = 0; i < paragraphCount; i++) {
      const effect = slide.Timeline.MainSequence.AddEffect(textShape, pptModule.AnimationEffectType.FadedZoom);
      effect.SetStartEndParagraphs(i, i);
    }

    // Save the result file
    const outputFileName = 'AnimateParagraphs_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from VFS and download it
    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>Paragraph Animations</h1>
      <button onClick={animateParagraphs}>Animate each paragraph</button>
    </div>
  );
}

export default App;

The presentation after animating the paragraphs of the text:

The presentation after animating the paragraphs of the text


Play text letter by letter or word by word

When a sentence itself is what the audience should focus on, showing it all at once can feel abrupt, while revealing it letter by letter or word by word guides the eye through the line. A text effect can specify the grouping unit: letters make the text appear character by character, words make it appear word by word; the interval setting then controls how fast the groups follow each other.

Writing Result
effect.IterateType with AnimateType.Letter, AnimateType.Word Groups the text by letter or by word
effect.IterateTimeValue Sets the interval between two consecutive groups

The steps are:

  1. Load the font and the presentation into the VFS, then get the second slide and its text shape from the loaded presentation.
  2. Add an effect for the first paragraph and limit it with SetStartEndParagraphs(), set IterateType to AnimateType.Letter, then set the interval between letters with IterateTimeValue.
  3. Add another effect for the second paragraph and limit it as well, set IterateType to AnimateType.Word, then set the interval between words with IterateTimeValue.
  4. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and trigger the download.

The code for playing text letter by letter or word by word is as follows:

function App() {
  const iterateText = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check if the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Load the font and the presentation into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'en_AnimationText.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);

    // Get the second slide and its text shape
    const slide = ppt.Slides.get_Item(1);
    const textShape = slide.Shapes.get_Item(1);

    // The first paragraph plays letter by letter, with an interval of 10
    const letterEffect = slide.Timeline.MainSequence.AddEffect(textShape, pptModule.AnimationEffectType.FadedZoom);
    letterEffect.SetStartEndParagraphs(0, 0);
    letterEffect.IterateType = pptModule.AnimateType.Letter;
    letterEffect.IterateTimeValue = 10;

    // The second paragraph plays word by word, with an interval of 15
    const wordEffect = slide.Timeline.MainSequence.AddEffect(textShape, pptModule.AnimationEffectType.Float);
    wordEffect.SetStartEndParagraphs(1, 1);
    wordEffect.IterateType = pptModule.AnimateType.Word;
    wordEffect.IterateTimeValue = 15;

    // Save the result file
    const outputFileName = 'IterateText_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from VFS and download it
    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>Letter and Word Playback</h1>
      <button onClick={iterateText}>Letter and word playback</button>
    </div>
  );
}

export default App;

The presentation after playing text letter by letter or word by word:

Presentation after playing text letter by letter or word by word


FAQ

How to change the playback order of several animations

Cause: The main animation sequence keeps effects in the order they are added and fires them in that order during the show, so an effect added last always plays last.

Solution: Call AddEffect() in the order you need. If an effect has already been added in the wrong place, remove it with MainSequence.RemoveAt() and add it again in the correct order; a re-added effect goes to the end of the sequence. Set the paragraph range and timing again after re-adding:

const sequence = slide.Timeline.MainSequence;
sequence.RemoveAt(0); // remove the effect that is out of order
const effect = sequence.AddEffect(textShape, pptModule.AnimationEffectType.FadedZoom);
effect.SetStartEndParagraphs(0, 0);

How to set the duration, delay and repeat count of an animation

Cause: The default duration and trigger pace are fixed, so a slower explanation or a looping emphasis needs its own timing.

Solution: Use the effect's Timing to set the playback duration, trigger delay and repeat mode. Duration and TriggerDelayTime are in seconds; for a fixed number of repeats, set AnimationRepeatType to Number and give the count in RepeatCount:

const effect = slide.Timeline.MainSequence.get_Item(0);
effect.Timing.Duration = 1.5;          // play once for 1.5 seconds
effect.Timing.TriggerDelayTime = 0.5;  // wait 0.5 seconds after the trigger
effect.Timing.AnimationRepeatType = pptModule.AnimationRepeatType.Number;
effect.Timing.RepeatCount = 3;         // repeat three times

To keep the animation repeating until the slide is left, set AnimationRepeatType to UtilEndOfSlide.

How to make several paragraph animations run one after another

Cause: A newly added animation waits for a click, so several paragraphs need one click each and the pace of the explanation keeps breaking.

Solution: Set the effect's Timing.TriggerType to AnimationTriggerType.AfterPrevious, and the animation starts right after the previous one ends:

effect.Timing.TriggerType = pptModule.AnimationTriggerType.AfterPrevious;

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.

The same group of graphics often has to reappear on several slides: a process diagram, a legend, a decorative band that keeps a consistent style from page to page. Copying them by hand works for a page or two, but once the deck grows it is easy to leave one out, and moving a shape onto a page with a different layout usually means realigning its position and size again. Copying shapes with Spire.Presentation for JavaScript while the deck is generated keeps the same group of graphics consistent across pages and saves the repeated adjustment.

This article uses Spire.Presentation for JavaScript to copy shapes between 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 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.


Copy a specific shape to another slide

Reusing a graphic that is already laid out on another page is common when building a deck: the diagram introduced on an earlier slide is still needed later, and the sample shape on a template page has to appear on a content page as well. Copying a single shape takes only two values: where it sits in the source slide, and the target slide it should join. Its fill, outline and text travel with it, while the source slide stays as it was.

Writing Result
Presentation.Slides.get_Item(index) Returns a slide of the presentation by index; indexing starts at 0
slide.Shapes Returns all shapes of the slide
slide.Shapes.get_Item(index) Returns one shape of the slide by index
slide.Shapes.Count Returns the number of shapes on the slide
targetSlide.Shapes.AddShape(sourceShape) Copies the source shape to the target slide, keeping its position and size

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font and the presentation into the VFS, then create a Presentation object and load the file.
  2. Get the source slide and the target slide through Presentation.Slides.get_Item().
  3. Take the shape to copy with the source slide's Shapes.get_Item() and hand it to the target slide's Shapes.AddShape().
  4. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and trigger the download.

The code for copying a specific shape to another slide is as follows:

function App() {
  const copyShape = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check if the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Load the font and the presentation into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'en_ShapeDeck.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);

    // Specify the source slide and the target slide
    const sourceSlide = ppt.Slides.get_Item(0);
    const targetSlide = ppt.Slides.get_Item(1);

    // Copy the second shape of the source slide to the target slide
    targetSlide.Shapes.AddShape(sourceSlide.Shapes.get_Item(1));

    // Save the result file
    const outputFileName = 'CopyShape_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from VFS and download it
    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>Copy Shapes Between Slides</h1>
      <button onClick={copyShape}>Copy a shape</button>
    </div>
  );
}

export default App;

The presentation after copying a specific shape to another slide:

Presentation after copying a specific shape to another slide


Copy all shapes of one slide to another slide

A slide usually holds a title, some text blocks and several shapes, and copying them one by one is both tedious and easy to get wrong. With the shape collection, every shape of the source slide can be taken by index and copied to the target slide in turn, so the target page receives the same set of content. When the target is a blank page, it can serve directly as a complete content page once the copy finishes.

The steps are:

  1. Load the font and the presentation into the VFS, then get the source slide and the target slide from the loaded presentation.
  2. Loop up to Shapes.Count and take each shape of the source slide with Shapes.get_Item().
  3. Hand each shape to the target slide's Shapes.AddShape() inside the loop to finish the whole-slide copy.
  4. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and trigger the download.

The code for copying all shapes of one slide to another slide is as follows:

function App() {
  const copyAllShapes = async () => {
    // Get the Spire.Presentation WASM module
    const pptModule = window.wasmModule?.spirepresentation;

    // Check if the module is ready
    if (!pptModule) {
      alert('Spire.Presentation is not ready yet');
      return;
    }

    // Load the font and the presentation into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'en_ShapeDeck.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the presentation
    const ppt = new pptModule.Presentation();
    ppt.LoadFromFile(inputFileName);

    // Specify the source slide and the blank target slide
    const sourceSlide = ppt.Slides.get_Item(0);
    const targetSlide = ppt.Slides.get_Item(2);

    // Take each shape of the source slide and copy it to the target slide
    for (let i = 0; i < sourceSlide.Shapes.Count; i++) {
      targetSlide.Shapes.AddShape(sourceSlide.Shapes.get_Item(i));
    }

    // Save the result file
    const outputFileName = 'CopyAllShapes_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from VFS and download it
    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>Copy All Shapes</h1>
      <button onClick={copyAllShapes}>Copy all shapes</button>
    </div>
  );
}

export default App;

The presentation after copying all shapes of one slide to another slide:

Presentation after copying all shapes of one slide to another slide


FAQ

Does a copied shape keep its original fill and text formatting

Cause: Besides the outline and position, the text inside the shape, its fill color and font size also need to survive the copy so the source page's layout can be reused as is.

Solution: AddShape() copies the shape itself, so fill, outline, text and font settings all come along. Get the shape back after copying and read Fill and TextFrame to confirm:

const copiedShape = targetSlide.Shapes.get_Item(targetSlide.Shapes.Count - 1);
console.log(copiedShape.Fill.SolidColor.Color.ToString());
console.log(copiedShape.TextFrame.Text, copiedShape.TextFrame.TextRange.FontHeight);

How to adjust the position and size of a copied shape

Cause: A copied shape keeps the coordinates it had on the source slide, so it lands in the same spot on the target page. When the target page is laid out differently, or the graphic should sit elsewhere, it has to be adjusted after the copy.

Solution: Get the shape back through the last index of the collection, then set Left, Top, Width and Height:

const copiedShape = targetSlide.Shapes.get_Item(targetSlide.Shapes.Count - 1);
copiedShape.Left = 470;
copiedShape.Top = 170;
copiedShape.Width = 160;
copiedShape.Height = 100;

How to copy a shape to another presentation

Cause: Graphics tend to accumulate in template files and earlier projects, so redrawing them for a new deck is expensive.

Solution: The shape object passed in is not bound to a particular presentation. Load the source presentation and the target presentation, hand the source shape to a slide of the target, and save the target:

const sourcePpt = new pptModule.Presentation();
sourcePpt.LoadFromFile('source.pptx');
const targetPpt = new pptModule.Presentation();
targetPpt.Slides.get_Item(0).Shapes.AddShape(sourcePpt.Slides.get_Item(0).Shapes.get_Item(0));
targetPpt.SaveToFile({ file: 'output.pptx', fileFormat: pptModule.FileFormat.Pptx2013 });

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.

Animations decide how and when the content of a presentation appears on screen. If shapes, titles and bullet points all show up at once, the audience has to keep up with the whole page at the same time; setting the animations page by page by hand takes time and is hard to keep consistent in a batch of generated decks. Adding animations with Spire.Presentation for JavaScript lets you arrange the order of every slide while the presentation is being generated, so the content and its effects are reused together.

This article uses Spire.Presentation for JavaScript to add animations to PowerPoint shapes 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 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 entrance animations to PowerPoint shapes

A newly added shape has no motion when the slide show starts. Once an entrance animation is assigned, the shape appears in turn along the animation sequence, so the content can be revealed piece by piece instead of all at once. The animations of a slide are stored in one main sequence, ordered by the time they are added, and they fire in that order during the slide show.

Writing Result
slide.Timeline.MainSequence Returns the main animation sequence of the current slide, holding the effects in order
MainSequence.AddEffect(shape, effectType) Adds an animation effect to a shape and returns the effect object
AnimationEffectType.FadedSwivel, FadedZoom, Float, etc. Selects the entrance effect, such as faded swivel, faded zoom or float
slide.Shapes.AppendShape({ shapeType, rectangle }) Adds a shape in the specified area of the slide

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, and create a Presentation object.
  2. Get the first slide through Presentation.Slides.get_Item(0).
  3. Add a title text box and three shapes with Shapes.AppendShape(), and set their fill and outline through Fill and Line.
  4. Call slide.Timeline.MainSequence.AddEffect() in turn with AnimationEffectType.FadedSwivel, FadedZoom and Float, one for each shape.
  5. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from the VFS and trigger the download.

The code for adding entrance animations to PowerPoint shapes:

function App() {
  const addEntranceAnimation = 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 title text box
    const title = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Rectangle,
      rectangle: pptModule.RectangleF.FromLTRB(60, 60, 660, 140),
    });
    title.Fill.FillType = pptModule.FillFormatType.None;
    title.Line.FillType = pptModule.FillFormatType.None;
    title.AppendTextFrame('Shape Animation Demo');
    title.TextFrame.TextRange.FontHeight = 32;
    title.TextFrame.TextRange.Fill.FillType = pptModule.FillFormatType.Solid;
    title.TextFrame.TextRange.Fill.SolidColor.Color = pptModule.Color.get_Black();
    title.TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Center;

    // Add three shapes
    const triangle = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Triangle,
      rectangle: pptModule.RectangleF.FromLTRB(90, 240, 190, 340),
    });
    triangle.Fill.FillType = pptModule.FillFormatType.Solid;
    triangle.Fill.SolidColor.Color = pptModule.Color.get_CadetBlue();
    triangle.Line.FillType = pptModule.FillFormatType.Solid;
    triangle.Line.SolidFillColor.Color = pptModule.Color.get_White();

    const rectangle = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Rectangle,
      rectangle: pptModule.RectangleF.FromLTRB(250, 240, 430, 340),
    });
    rectangle.Fill.FillType = pptModule.FillFormatType.Solid;
    rectangle.Fill.SolidColor.Color = pptModule.Color.get_LightSkyBlue();
    rectangle.Line.FillType = pptModule.FillFormatType.Solid;
    rectangle.Line.SolidFillColor.Color = pptModule.Color.get_White();
    rectangle.AppendTextFrame('Animated Shape');
    rectangle.TextFrame.TextRange.FontHeight = 24;

    const cloud = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Cloud,
      rectangle: pptModule.RectangleF.FromLTRB(500, 235, 620, 345),
    });
    cloud.Fill.FillType = pptModule.FillFormatType.Solid;
    cloud.Fill.SolidColor.Color = pptModule.Color.get_White();
    cloud.Line.FillType = pptModule.FillFormatType.Solid;
    cloud.Line.SolidFillColor.Color = pptModule.Color.get_CadetBlue();

    // Add entrance animations to the three shapes in order
    slide.Timeline.MainSequence.AddEffect(triangle, pptModule.AnimationEffectType.FadedSwivel);
    slide.Timeline.MainSequence.AddEffect(rectangle, pptModule.AnimationEffectType.FadedZoom);
    slide.Timeline.MainSequence.AddEffect(cloud, pptModule.AnimationEffectType.Float);

    // Save the result file
    const outputFileName = 'AddEntranceAnimation_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>Shape Animation</h1>
      <button onClick={addEntranceAnimation}>Add entrance animation</button>
    </div>
  );
}

export default App;

Presentation after adding entrance animations to three shapes:

Presentation after adding entrance animations to three shapes

Add exit animations to shapes

An entrance animation brings a shape in; an exit animation takes it away once the topic has been covered, freeing the page for what comes next. Call AddEffect() to add an effect, then set PresetClassType to TimeNodePresetClassType.Exit so the effect runs on exit instead of entrance:

const effect = slide.Timeline.MainSequence.AddEffect(shape, pptModule.AnimationEffectType.RandomBars);
effect.PresetClassType = pptModule.TimeNodePresetClassType.Exit;

Set animation duration, delay and repeat options

The default duration and trigger rhythm suit a single walk-through, but not content that needs emphasis or a longer stay on screen: some animations should be slowed down so the change is easy to follow, while others should keep repeating while the slide stays visible. Every effect object carries Timing, which controls the duration, delay and repeat mode separately without touching the effect type itself.

Writing Result
effect.Timing.Duration Sets how long one run of the animation takes, in seconds
effect.Timing.TriggerDelayTime Sets how long to wait after the trigger before playing, in seconds
Timing.AnimationRepeatType Sets how the animation repeats
AnimationRepeatType.UtilEndOfSlide Keeps playing until the slide is left
AnimationRepeatType.Number + Timing.RepeatCount Repeats the animation a fixed number of times

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, then create a Presentation object and get the first slide.
  2. Add two color blocks with Shapes.AppendShape() and set their fill colors.
  3. For the first block, call AddEffect() to add an animation, then set effect.Timing.Duration and effect.Timing.TriggerDelayTime.
  4. Set effect.Timing.AnimationRepeatType to AnimationRepeatType.UtilEndOfSlide, so the animation keeps playing until the slide is left.
  5. For the second block, add another animation, set Timing.AnimationRepeatType to AnimationRepeatType.Number, and give the count through Timing.RepeatCount.
  6. Save the result file, release the presentation, then read the file from the VFS and trigger the download.

The code for setting animation duration, delay and repeat options:

function App() {
  const setAnimationTiming = 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 two color blocks
    const firstBar = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Rectangle,
      rectangle: pptModule.RectangleF.FromLTRB(120, 180, 320, 360),
    });
    firstBar.Fill.FillType = pptModule.FillFormatType.Solid;
    firstBar.Fill.SolidColor.Color = pptModule.Color.get_CadetBlue();
    firstBar.Line.FillType = pptModule.FillFormatType.None;

    const secondBar = slide.Shapes.AppendShape({
      shapeType: pptModule.ShapeType.Rectangle,
      rectangle: pptModule.RectangleF.FromLTRB(400, 180, 600, 360),
    });
    secondBar.Fill.FillType = pptModule.FillFormatType.Solid;
    secondBar.Fill.SolidColor.Color = pptModule.Color.get_LightSkyBlue();
    secondBar.Line.FillType = pptModule.FillFormatType.None;

    // Add an animation to one block and set its duration and delay
    const effect = slide.Timeline.MainSequence.AddEffect(firstBar, pptModule.AnimationEffectType.FadedZoom);
    effect.Timing.Duration = 1.5;
    effect.Timing.TriggerDelayTime = 0.5;
    effect.Timing.AnimationRepeatType = pptModule.AnimationRepeatType.UtilEndOfSlide;

    // Add an animation to the other block and repeat it three times
    const loopEffect = slide.Timeline.MainSequence.AddEffect(secondBar, pptModule.AnimationEffectType.FadedSwivel);
    loopEffect.Timing.Duration = 1;
    loopEffect.Timing.AnimationRepeatType = pptModule.AnimationRepeatType.Number;
    loopEffect.Timing.RepeatCount = 3;

    // Save the result file
    const outputFileName = 'SetAnimationTiming_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>Shape Animation</h1>
      <button onClick={setAnimationTiming}>Set animation timing</button>
    </div>
  );
}

export default App;

Presentation after setting animation duration, delay and repeat options:

Presentation after setting animation duration, delay and repeat options


FAQ

How to read the animations already in a slide

Cause: When you keep working on an existing presentation, you need to know which animations each slide already has before deciding what to add or adjust.

Solution: Walk through the main sequence and read the effect type, target shape and duration of each effect:

const sequence = slide.Timeline.MainSequence;
for (let i = 0; i < sequence.Count; i++) {
  const effect = sequence.get_Item(i);
  console.log(effect.AnimationEffectType, effect.ShapeTarget.Name, effect.Timing.Duration);
}

How to play an animation after the previous one finishes

Cause: A new animation waits for a click by default, so several effects need one click each and the rhythm is easy to break.

Solution: Set Timing.TriggerType to AnimationTriggerType.AfterPrevious; the animation then starts as soon as the previous one ends. WithPrevious plays it together with the previous animation:

effect.Timing.TriggerType = pptModule.AnimationTriggerType.AfterPrevious;

Why animations do not show in exported images

Cause: Animations live in the animation timeline of the presentation and play in order during the slide show; an exported image is a still frame that only reflects the final style and position of the shapes.

Solution: Play the presentation in a viewer that supports animations to see the effect; exported images are suited to showing a single frame of layout, not the animation itself.


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.

When 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:

  1. Get the Spire.Presentation WASM module and make sure it is ready, then load the font file and the presentation into the VFS.
  2. Create a Presentation object, load the presentation with LoadFromFile(), and get the first slide with Slides.get_Item(0).
  3. Get the shape whose text overflows its border with Shapes.get_Item(index).
  4. Set the shape's TextFrame.AutofitType to TextAutofitType.Normal so the overflowing text shrinks to fit the shape.
  5. Save the presentation with SaveToFile(), release it with Presentation.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:

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:

  1. Get the Spire.Presentation WASM module and make sure it is ready, then load the font file and the presentation into the VFS.
  2. Create a Presentation object, load the presentation with LoadFromFile(), and get the first slide with Slides.get_Item(0).
  3. Get the shape that is much taller than its text with Shapes.get_Item(index).
  4. Set the shape's TextFrame.AutofitType to TextAutofitType.Shape so the shape shrinks to fit the content.
  5. Save the presentation with SaveToFile(), release it with Presentation.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:

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.

Titles, 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:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, and create a Presentation object.
  2. Get the first slide with Presentation.Slides.get_Item(0).
  3. Add a ShapeType.Rectangle shape with Shapes.AppendShape(), and define its position and size with RectangleF.FromLTRB().
  4. Set Fill.FillType and Line.FillType to FillFormatType.None to remove the fill and the outline of the text box.
  5. Call shape.AppendTextFrame() to write the text, then set the font size and the text color through TextFrame.TextRange, and center the paragraph.
  6. Call Presentation.SaveToFile() to save the result file and Dispose() 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:

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:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file into the VFS, create a Presentation object and get the first slide.
  2. Add a rectangle text box with Shapes.AppendShape(), and write two lines of text with shape.AppendTextFrame().
  3. Through TextFrame.TextRange, set the text to white at 30 points, specify the fonts with LatinFont and EastAsianFont, and center each paragraph.
  4. Set Line.FillType to FillFormatType.Solid, and use Line.Width and Line.SolidFillColor.Color to give the text box a white border.
  5. Set Fill.FillType to FillFormatType.Gradient, specify a linear gradient with GradientShape, and add the light blue and cadet blue stops with GradientStops.Append().
  6. Create an OuterShadowEffect, set BlurRadius, Direction, Distance and ColorFormat.Color, and assign it to EffectDag.OuterShadowEffect.
  7. 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:

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.

Laying out a slide often means adjusting the rotation angle, position, and stacking order of shapes over and over: a tilted label adds movement, an element pushed into a corner unbalances the page, and when shapes overlap, a shape added later can hide content that should stand out. Dragging by hand is intuitive, but it is hard to reproduce the same angle and coordinates exactly, and batch changes take even longer.

Spire.Presentation for JavaScript controls a shape's orientation, position, and overlap through its rotation angle, top-left coordinates, and stacking order. The whole process runs locally in the browser through WebAssembly, requires no Office installation and no back-end service, and the presentation never leaves the user's device.

The article covers three 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.


Rotate PowerPoint Shapes

Rotating a shape is a common way to emphasize an element or add a sense of movement. Reproducing the same angle by hand is difficult, and adjusting shapes one by one takes time. The Rotation property sets the angle in degrees; positive values rotate clockwise, the shape turns around its own center, and any text inside the shape tilts with it.

Code Result
Shapes.get_Item(index) Gets a shape on the slide by index
shape.Rotation Sets the rotation angle in degrees; positive values rotate clockwise

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, then load the font file and the presentation into the VFS.
  2. Create a Presentation object, load the presentation with LoadFromFile(), and get the first slide with Slides.get_Item(0).
  3. Get the shape to rotate with Shapes.get_Item(index); the index starts at 0.
  4. Assign the angle in degrees to shape.Rotation; positive values rotate clockwise. Rotation happens around the shape center, while Left, Top, Width, and Height stay unchanged.
  5. Call SaveToFile() to save the presentation, call Presentation.Dispose() to release resources, then read the file from the VFS and trigger the download.

The code for rotating a PowerPoint shape is shown below:

function App() {
  const rotateShape = 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 and the presentation into the VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'ShapeLayout.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);

    // Get the shape to rotate
    const shape = slide.Shapes.get_Item(1);

    // Rotate 30 degrees clockwise
    shape.Rotation = 30;

    // Save the presentation
    const outputFileName = 'RotateShape_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });

    // Release the presentation
    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>Rotate Shape</h1>
      <button onClick={rotateShape}>
        Rotate
      </button>
    </div>
  );
}

export default App;

Presentation after rotating a shape clockwise:

Presentation after rotating a shape clockwise


Move PowerPoint Shapes

A shape's position is determined by its top-left coordinates in points, with the origin at the top-left corner of the slide. Compared with dragging, setting coordinates directly makes alignment exact and lets you compute centered or edge-aligned positions from the slide size, without drift caused by canvas zoom.

Code Result
shape.Left Distance from the shape's left edge to the slide's left edge
shape.Top Distance from the shape's top edge to the slide's top edge
ppt.SlideSize.Size.Width Slide width
ppt.SlideSize.Size.Height Slide height
shape.Width / shape.Height Shape dimensions, used to compute the centered position

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, then load the font file and the presentation into the VFS.
  2. Create a Presentation object, load the presentation with LoadFromFile(), and get the first slide with Slides.get_Item(0).
  3. Get the shape to move with Shapes.get_Item(index).
  4. Read the slide size with ppt.SlideSize.Size.Width and ppt.SlideSize.Size.Height, then use the shape's Width and Height to compute the horizontally centered position and the bottom margin.
  5. Assign the results to shape.Left and shape.Top, save the presentation, release resources, and download the result.

The code for moving a PowerPoint shape is shown below:

function App() {
  const moveShape = 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 and the presentation into the VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'ShapeLayout.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);

    // Get the shape to move
    const shape = slide.Shapes.get_Item(2);

    // Compute a horizontally centered position with a 40-point bottom margin from the slide size
    const margin = 40;
    shape.Left = (ppt.SlideSize.Size.Width - shape.Width) / 2;
    shape.Top = ppt.SlideSize.Size.Height - shape.Height - margin;

    // Save the presentation
    const outputFileName = 'MoveShape_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });

    // Release the presentation
    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>Move Shape</h1>
      <button onClick={moveShape}>
        Move
      </button>
    </div>
  );
}

export default App;

Presentation after moving a shape to the bottom center:

Presentation after moving a shape to the bottom center


Reorder PowerPoint Shapes

Shapes on a slide are stacked in the order they were added, so a later shape covers an earlier one. When elements overlap, content that should stand out can end up underneath, and a background block can hide text. SetShapeArrange() provides four adjustments—bring forward, send backward, bring to front, and send to back—for fine-grained control over the stacking order.

Code Result
shape.SetShapeArrange(ShapeArrange.BringForward) Moves the shape one layer forward
shape.SetShapeArrange(ShapeArrange.SendBackward) Moves the shape one layer backward
shape.SetShapeArrange(ShapeArrange.BringToFront) Moves the shape to the front
shape.SetShapeArrange(ShapeArrange.SendToBack) Moves the shape to the back

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, then load the font file and the presentation into the VFS.
  2. Create a Presentation object, load the presentation with LoadFromFile(), and get the first slide with Slides.get_Item(0).
  3. Get the shape whose stacking order should change with Shapes.get_Item(index), then call SetShapeArrange() with the required ShapeArrange value.
  4. Call SaveToFile() to save the presentation, call Presentation.Dispose() to release resources, then read the file from the VFS and trigger the download.

The code for bringing a PowerPoint shape to the front is shown below:

function App() {
  const bringShapeToFront = 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 and the presentation into the VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'ShapeLayout.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);

    // Get the shape whose stacking order should change and bring it to the front
    const shape = slide.Shapes.get_Item(0);
    shape.SetShapeArrange(pptModule.ShapeArrange.BringToFront);

    // Save the presentation
    const outputFileName = 'BringToFront_result.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });

    // Release the presentation
    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>Adjust Stacking Order</h1>
      <button onClick={bringShapeToFront}>
        Bring to Front
      </button>
    </div>
  );
}

export default App;

Presentation after bringing a shape to the front:

Presentation after bringing a shape to the front


FAQ

Does a shape's position change after rotation

Reason: Rotation only changes the rotation angle; it does not modify Left, Top, Width, or Height. The shape rotates around its center, so the rotated footprint can extend beyond the original rectangle.

Solution: When reserving space for a rotated shape, estimate margins from the rotated footprint rather than the original width and height.

What happens when the rotation angle exceeds 360 degrees

Reason: Rotation is normalized modulo 360. Setting 390 reads back as 30, setting 360 reads back as 0, and the normalized angle is what gets saved in the presentation.

Solution: Set the required angle in the 0–360 range directly; there is no need to add whole turns.

Does the text rotate with the shape

Reason: Rotation applies to the whole shape. Text inside the shape is part of it, so it tilts along with the shape.

Solution: Reserve space for the tilted text when laying out the slide. If the text must stay horizontal, do not put it inside the shape being rotated; use a separate text box and handle it independently from the graphic.


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.

Product intros and quarterly reports often need pictures on the slides. Adding one to a single page is a page-by-page job; to put a company logo on every slide, you have to edit the slide master. In desktop software, that means switching to master view and aligning the position by hand; running it on the server means uploading the file first.

This article adds images to PowerPoint directly in the browser with Spire.Presentation for JavaScript. A picture can go onto one slide, or onto the slide master so every slide using that master shows it. The whole process runs in the browser via WebAssembly, with no Office installation and no backend dependency, and the file always stays on the user's device.

This article covers two core tasks:

For installation and project setup, see Integrate Spire.Presentation for JavaScript in a React project. The examples below assume Spire.Presentation is installed and the WebAssembly module is initialized.


Insert a picture into a slide

Spire.Presentation for JavaScript provides Shapes.AppendEmbedImage() to add a picture directly to a slide.

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the scenery image and fonts, create a Presentation object as a new blank presentation.
  3. Define the picture rectangle with RectangleF.FromLTRB(); the four values are left, top, right, bottom.
  4. Call Shapes.AppendEmbedImage() on the blank slide that comes with the new presentation, passing ShapeType.Rectangle, the image file name, and the rectangle; it returns the picture shape.
  5. Save the result, read it from the VFS, and trigger a browser download.

The code to insert a picture into a slide is as follows:

function App() {
  const insertPicture = 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 scenery image and fonts
    await window.spire.FetchFileToVFS('Scenery.png', "", `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('ARIALUNI.TTF', "/Library/Fonts/", `${process.env.PUBLIC_URL}/font/`);

    // Create a new blank presentation (it comes with one blank slide) and set it to 16:9
    const ppt = new pptModule.Presentation();
    ppt.SlideSize.Type = pptModule.SlideSizeType.Screen16x9;

    // Rectangle is in points, origin at the top-left of the slide
    const rect = pptModule.RectangleF.FromLTRB(300, 135, 660, 405);

    // Append a picture shape to the new blank slide
    const slide = ppt.Slides.get_Item(0);
    const picture = slide.Shapes.AppendEmbedImage({
      shapeType: pptModule.ShapeType.Rectangle,
      fileName: 'Scenery.png',
      rectangle: rect,
    });

    // Remove the border that comes with the picture shape
    picture.Line.FillType = pptModule.FillFormatType.None;

    // Save the result file
    const outputFileName = 'Inserted-Image.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and trigger a 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>Insert a picture into a slide</h1>
      <button id="btn-1" onClick={insertPicture}>
        Insert picture
      </button>
    </div>
  );
}

export default App;

The picture now sits in the center of the slide:

The picture now sits in the center of the slide


Add an image to the slide master

Slide masters are managed by Presentation.Masters. Adding a picture to the master with Shapes.AppendEmbedImage() makes every slide using that master show it.

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the logo image and fonts, create a Presentation object as a new blank presentation.
  3. Get the default slide master with Presentation.Masters.get_Item(0).
  4. Define the picture area with RectangleF.FromLTRB(), call AppendEmbedImage() on the master's Shapes, and remove the picture border.
  5. Call Slides.Append() to add a slide, save the result, read it from the VFS, and trigger a browser download.

The code to add an image to the slide master is as follows:

function App() {
  const addImageToSlideMaster = 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 logo image and fonts
    await window.spire.FetchFileToVFS('Logo.png', "", `${process.env.PUBLIC_URL}/data/`);
    await window.spire.FetchFileToVFS('ARIALUNI.TTF', "/Library/Fonts/", `${process.env.PUBLIC_URL}/font/`);

    // Create a new blank presentation and set it to 16:9
    const ppt = new pptModule.Presentation();
    ppt.SlideSize.Type = pptModule.SlideSizeType.Screen16x9;

    // Get the default slide master
    const master = ppt.Masters.get_Item(0);

    // Append a picture shape to the master; rectangle is in points
    const rect = pptModule.RectangleF.FromLTRB(40, 40, 130, 130);
    const picture = master.Shapes.AppendEmbedImage({
      shapeType: pptModule.ShapeType.Rectangle,
      fileName: 'Logo.png',
      rectangle: rect,
    });

    // Remove the border that comes with the picture shape
    picture.Line.FillFormat.FillType = pptModule.FillFormatType.None;

    // Add a slide to see the master image in effect
    ppt.Slides.Append();

    // Save the result file
    const outputFileName = 'Master-Image.pptx';
    ppt.SaveToFile({ file: outputFileName, fileFormat: pptModule.FileFormat.Pptx2013 });
    ppt.Dispose();

    // Read the generated file from the VFS and trigger a 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 an image to the slide master</h1>
      <button id="btn-2" onClick={addImageToSlideMaster}>
        Add image to master
      </button>
    </div>
  );
}

export default App;

The master image now appears on the newly added slide:

The master image now appears on the newly added slide


FAQ

Why does the inserted picture appear somewhere else on the slide

The four values of RectangleF.FromLTRB() are in points, with the origin at the top-left of the slide, and they are left, top, right, bottom — not width and height. The picture's top-left corner lands at (left, top), and its size is right - left by bottom - top. Convert coordinates against the slide size first; a 16:9 page is 960 × 540 points.

What is the difference between a master image and a regular picture

A picture on the master is part of the layout: every slide using that master shows it, its position is fixed, and it cannot be selected or deleted on an individual slide. A regular picture belongs only to the slide it was inserted on and can be moved or removed there.

Why is the master image hidden behind slide content

Master pictures render below slide content, so text and shapes on the slide cover them. Place the master image in an empty area of the page, or adjust the layout of the slide content.

Can I add more than one image at a time

Yes. Call AppendEmbedImage() once per image, on a slide or a master. When adding several to the same slide or master, pass a different rectangle each time so they do not overlap. The output is still one PPTX file, saved once.


Get a Free License

If you want to remove the evaluation message from the result documents or lift feature limits, contact sales for a temporary license valid for 30 days.

Page 1 of 2
page 1