Insert Pictures into PowerPoint Table Cells in React

Tables in a slide deck often carry portraits, product shots or stamps. Inserting a picture cell by cell and then dragging it into place takes time as soon as the rows pile up, and keeping the scale uniform is hard; nudge the table width and gaps appear between the picture and the cell. Used as the fill of a cell, a picture becomes part of the cell: it follows the row height and column width, and the table always looks tidy.

This article uses Spire.Presentation for JavaScript to insert pictures into PowerPoint table cells 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.


Insert a picture into a PowerPoint table cell

A picture used as a cell fill shares the cell's area: when the row height or the column width changes, the picture follows and leaves no blank edge. The picture is embedded only once and can serve several cells, so the file does not grow with every copy. The stretch fill spreads the picture over the whole cell, which suits portraits and thumbnails that should be shown in full.

What you write What you get
new pptModule.Stream(imgFileName) Opens a file stream for the picture in the VFS
ppt.Images.Append({ stream: stream }) Embeds the picture from the stream and returns it
cell.FillFormat.FillType = pptModule.FillFormatType.Picture Makes the fill of the cell a picture
cell.FillFormat.PictureFill.Picture.EmbedImage = image Uses the embedded picture as the fill
cell.FillFormat.PictureFill.FillType = pptModule.PictureFillType.Stretch Stretches the picture over the whole cell

The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the presentation and the picture into the VFS, create a Presentation object and load the file with LoadFromFile(), then take the first slide with Slides.get_Item(0).
  2. Walk the shape collection up to Shapes.Count and find the table with shape instanceof pptModule.ITable.
  3. Open the picture with new pptModule.Stream(), embed it with ppt.Images.Append(), then close the stream with stream.Close().
  4. Walk the icon cells row by row, set cell.FillFormat.FillType to FillFormatType.Picture, choose the picture with PictureFill.Picture.EmbedImage and set PictureFill.FillType to PictureFillType.Stretch.
  5. Save the result with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file from the VFS and start the download.

The code that inserts a picture into a PowerPoint table cell is as follows:

function App() {
  // insert a picture into a PowerPoint table cell
  const insertCellImage = 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 and the picture into the VFS
    const inputFileName = 'en_CellImage.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
    const imgFileName = 'photo.png';
    await window.spire.FetchFileToVFS(imgFileName, '', `${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 shape collection and find the table by type
    let table = null;
    for (let i = 0; i < slide.Shapes.Count; i++) {
      const shape = slide.Shapes.get_Item(i);
      if (shape instanceof pptModule.ITable) {
        table = shape;
        break;
      }
    }

    // read the picture from a file stream and embed it
    const stream = new pptModule.Stream(imgFileName);
    const image = ppt.Images.Append({ stream: stream });
    stream.Close();

    // fill the icon cells with the picture, stretched to the cell size
    for (let row = 1; row < table.TableRows.Count; row++) {
      const cell = table.get_Item(1, row);
      cell.FillFormat.FillType = pptModule.FillFormatType.Picture;
      cell.FillFormat.PictureFill.Picture.EmbedImage = image;
      cell.FillFormat.PictureFill.FillType = pptModule.PictureFillType.Stretch;
    }

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

    // read the generated file from the VFS and start the download
    downloadFile(outputFileName);
  };

  // read the generated file from the VFS and start the download
  const downloadFile = (outputFileName) => {
    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>Pictures in PowerPoint Table Cells</h1>
      <button onClick={insertCellImage}>Insert a picture</button>
    </div>
  );
}

export default App;

Presentation after inserting a picture into a PowerPoint table cell:

Presentation after inserting a picture into a PowerPoint table cell


Crop the picture in a PowerPoint table cell

Only part of the original picture is often needed; stretching the whole frame would enlarge the empty margins along with it. The crop area is described as a relative rectangle: the position of the top-left corner and the width and height are given as ratios of the picture's sides, between 0 and 1. Shrinking that rectangle keeps only the matching part of the picture and drops the rest, so the cell shows a close-up.

What you write What you get
cell.FillFormat.PictureFill.SourceRectangle Gets the crop area of the picture as a relative rectangle
cropArea.X = 0.2 The left edge of the crop area sits two tenths in from the left
cropArea.Y = 0.1 The top edge sits one tenth down from the top
cropArea.Width = 0.6 The crop area spans six tenths of the picture's width
cropArea.Height = 0.6 The crop area spans six tenths of the picture's height

The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the presentation and the picture into the VFS, create a Presentation object and load the file with LoadFromFile(), then take the first slide with Slides.get_Item(0).
  2. Walk the shape collection up to Shapes.Count and find the table with shape instanceof pptModule.ITable.
  3. Open the picture with new pptModule.Stream(), embed it with ppt.Images.Append(), then close the stream with stream.Close().
  4. Walk the icon cells, set them to a picture fill with Stretch, take PictureFill.SourceRectangle and set X, Y, Width and Height so that only the middle part of the picture is kept.
  5. Save the result with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file from the VFS and start the download.

The code that crops the picture in a PowerPoint table cell is as follows:

function App() {
  // crop the picture in a table cell
  const cropCellImage = 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 and the picture into the VFS
    const inputFileName = 'en_CellImage.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
    const imgFileName = 'photo.png';
    await window.spire.FetchFileToVFS(imgFileName, '', `${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 shape collection and find the table by type
    let table = null;
    for (let i = 0; i < slide.Shapes.Count; i++) {
      const shape = slide.Shapes.get_Item(i);
      if (shape instanceof pptModule.ITable) {
        table = shape;
        break;
      }
    }

    // read the picture from a file stream and embed it
    const stream = new pptModule.Stream(imgFileName);
    const image = ppt.Images.Append({ stream: stream });
    stream.Close();

    // fill the icon cells and keep only the middle area of the icon
    for (let row = 1; row < table.TableRows.Count; row++) {
      const cell = table.get_Item(1, row);
      cell.FillFormat.FillType = pptModule.FillFormatType.Picture;
      cell.FillFormat.PictureFill.Picture.EmbedImage = image;
      cell.FillFormat.PictureFill.FillType = pptModule.PictureFillType.Stretch;
      const cropArea = cell.FillFormat.PictureFill.SourceRectangle;
      cropArea.X = 0.2;
      cropArea.Y = 0.1;
      cropArea.Width = 0.6;
      cropArea.Height = 0.6;
    }

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

    // read the generated file from the VFS and start the download
    downloadFile(outputFileName);
  };

  // read the generated file from the VFS and start the download
  const downloadFile = (outputFileName) => {
    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>Pictures in PowerPoint Table Cells</h1>
      <button onClick={cropCellImage}>Crop the picture</button>
    </div>
  );
}

export default App;

Presentation after cropping the picture in a PowerPoint table cell:

Presentation after cropping the picture in a PowerPoint table cell


FAQ

How do I remove a picture fill from a cell

Cause: A picture fill is one of the fill types of the cell; making the cell blank again takes a change of the fill type, not the removal of the picture object.

Solution: Set cell.FillFormat.FillType to FillFormatType.None and the cell goes back to an empty fill:

cell.FillFormat.FillType = pptModule.FillFormatType.None;

Does the text in a cell get hidden behind the picture

Cause: The picture fill sits at the bottom of the cell, while the text is content of the cell, and the two are stored in separate layers.

Solution: Nothing extra is needed. After the picture fill is applied, the text of the cell still shows above the picture; clear TextFrame.Text if a blank area is wanted instead.

Does the picture distort when rows and columns are resized

Cause: A picture fill is attached to the cell, so the fill area changes together with the cell.

Solution: With PictureFillType.Stretch the picture stretches along with the cell; to keep the pattern in proportion, use PictureFillType.Tile with a fixed scale instead.


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.