Edit, Replace or Delete Images in PowerPoint in React with JavaScript

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.