Speaker notes are the script that lives outside the slides: talking points, timing reminders, and ad-lib lines the audience never sees during a show. When you organize courseware, reuse templates, or export meeting notes as text, you often need to write, pull out, or clear these notes in bulk. Doing it page by page in a desktop app gets slow once a deck grows, and uploading files to a server takes the content off the user's machine.

This article uses Spire.Presentation for JavaScript to add, read, and delete speaker notes in the browser. The whole process runs on WebAssembly and reads and writes pptx through a virtual file system (VFS), so it needs no Office install and no backend.

The article covers three core features:

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.


Add Speaker Notes to a PowerPoint Slide

Spire.Presentation for JavaScript provides the AddNotesSlide() method to create a notes slide for a given slide, then writes the note text through NotesTextFrame.Text.

Approach What gets written
NotesTextFrame.Text = '...' One block of text covering the whole notes slide
NotesTextFrame.Paragraphs.AppendoTextParagraph(p) Appends one paragraph, which can have its own bullet

Steps:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the sample presentation and create a Presentation object.
  3. Use Slides.get_Item() to get the target slide, call AddNotesSlide() to create a notes slide, then write NotesTextFrame.Text.
  4. Save the result with Presentation.SaveToFile().
  5. Read the result file from the VFS and trigger a browser download.

Code:

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

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

    // Load the sample presentation
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', "", `${process.env.PUBLIC_URL}/data/`);

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

    // Get the second slide, which has no notes slide yet
    const slide = ppt.Slides.get_Item(1);

    // Create a notes slide, then write the note text
    const notesSlide = slide.AddNotesSlide();
    notesSlide.NotesTextFrame.Text = 'Start with a full product overview, then walk through the features page by page. Slow down when you reach data security and leave room for questions.';

    // Save the result file
    const outputFileName = 'PresentationWithSpeakerNotes.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 Speaker Notes</h1>
      <button onClick={addSpeakerNotes}>
        Add Speaker Notes
      </button>
    </div>
  );
}

export default App;

The note appears on the notes slide of the second slide:

Presentation after adding speaker notes

Write Notes in Paragraphs with Numbered Bullets

For a step-by-step checklist, append paragraphs one by one with Paragraphs.AppendoTextParagraph(), then turn each into a numbered list:

// Create a notes slide, then append paragraphs with their own numbering
const notesSlide = ppt.Slides.get_Item(1).AddNotesSlide();
const frame = notesSlide.NotesTextFrame;

const first = new pptModule.TextParagraph();
first.Text = 'Prepare the script';
frame.Paragraphs.AppendoTextParagraph(first);
frame.Paragraphs.get_Item(1).BulletType = pptModule.TextBulletType.Numbered;
frame.Paragraphs.get_Item(1).BulletStyle = pptModule.NumberedBulletStyle.BulletArabicPeriod;

const second = new pptModule.TextParagraph();
second.Text = 'Keep one core message per slide and trim the word count';
frame.Paragraphs.AppendoTextParagraph(second);
frame.Paragraphs.get_Item(2).BulletType = pptModule.TextBulletType.Numbered;
frame.Paragraphs.get_Item(2).BulletStyle = pptModule.NumberedBulletStyle.BulletArabicPeriod;

Read Speaker Notes from a PowerPoint File

Spire.Presentation for JavaScript also gets the notes slide via slide.NotesSlide, then reads the full note text through NotesTextFrame.Text.

Steps:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the sample presentation and create a Presentation object.
  3. Use Slides.get_Item() to get the target slide, then read the note text through NotesSlide.NotesTextFrame.Text.
  4. Write the result into a txt file.
  5. Read the result file from the VFS and trigger a browser download.

Code:

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

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

    // Load the sample presentation
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', "", `${process.env.PUBLIC_URL}/data/`);

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

    // Get the notes slide of the first slide and read all note text
    const slide = ppt.Slides.get_Item(0);
    const notesText = slide.NotesSlide.NotesTextFrame.Text;

    // Write the notes into a txt file
    const outputFileName = 'SpeakerNotes.txt';
    const content = `Speaker notes on slide 1:\n${notesText}`;
    window.dotnetRuntime.Module.FS.writeFile(outputFileName, content);
    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: 'text/plain' });
    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 Speaker Notes</h1>
      <button onClick={readSpeakerNotes}>
        Read Speaker Notes
      </button>
    </div>
  );
}

export default App;

The exported txt file holds the full notes of the first slide:

Exported speaker notes text file


Delete Speaker Notes from a PowerPoint File

Spire.Presentation for JavaScript can clear the whole notes slide by assigning an empty string to NotesTextFrame.Text, or delete one paragraph by index with Paragraphs.RemoveAt().

Approach Effect
NotesTextFrame.Text = '' Clears all text on the notes slide; the notes slide stays but is empty
NotesTextFrame.Paragraphs.RemoveAt(index) Deletes only the paragraph at the given index; the rest stay

Steps:

  1. Get the Spire.Presentation WASM module and make sure it is ready.
  2. Load the sample presentation and create a Presentation object.
  3. Use Slides.get_Item() to get the target slide, then assign an empty string to NotesSlide.NotesTextFrame.Text.
  4. Save the result with Presentation.SaveToFile().
  5. Read the result file from the VFS and trigger a browser download.

Code:

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

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

    // Load the sample presentation
    await window.spire.FetchFileToVFS('SamplePresentation.pptx', "", `${process.env.PUBLIC_URL}/data/`);

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

    // Get the notes slide of the first slide and clear the note text
    const slide = ppt.Slides.get_Item(0);
    slide.NotesSlide.NotesTextFrame.Text = '';

    // Save the result file
    const outputFileName = 'PresentationWithoutSpeakerNotes.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 Speaker Notes</h1>
      <button onClick={removeSpeakerNotes}>
        Delete Speaker Notes
      </button>
    </div>
  );
}

export default App;

After clearing, the notes slide of the first slide holds no text:

Presentation after deleting speaker notes

Delete a Specific Notes Paragraph

To drop just one paragraph and keep the rest, use Paragraphs.RemoveAt() with an index:

// Delete only the given paragraph of the first slide's notes and keep the rest
const frame = ppt.Slides.get_Item(0).NotesSlide.NotesTextFrame;
frame.Paragraphs.RemoveAt(1);

FAQ

Do speaker notes show up during the slideshow

Cause: Speaker notes live on a separate notes slide. They are the presenter's script and are stored apart from the slide content.

Fix: The audience only sees the slide content during a show. Notes appear in Presenter View or the editing window, so read the notes slide when you need to adjust the talking points.

Can I read or delete notes on a slide that never had any

Cause: A slide with no notes slide has no note text to read, and clearing it does nothing.

Fix: Call AddNotesSlide() to create a notes slide and write content first, then read and write through NotesSlide.NotesTextFrame. In batch jobs, check whether a slide already has a notes slide before operating on it.

Should I clear the whole page or delete paragraph by paragraph

Cause: NotesTextFrame.Text addresses the whole notes slide, while Paragraphs addresses individual paragraphs.

Fix: To clear everything, assign an empty string with Text = ''. To remove just one paragraph, use Paragraphs.RemoveAt(index).

Do notes support Chinese and bullets

Cause: The notes text frame stores text as Unicode, and each paragraph can have its own bullet type and style.

Fix: Write the string directly, including Chinese. For an ordered list, set BulletType = TextBulletType.Numbered and BulletStyle = NumberedBulletStyle.BulletArabicPeriod on the paragraph.

How do Text and Paragraphs relate

Cause: NotesTextFrame.Text treats the whole notes slide as one block of text, while Paragraphs manages it paragraph by paragraph.

Fix: Use Text to overwrite or read the whole page, and Paragraphs to append paragraphs or delete them by index.


Get a Free License

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

When several series sit side by side under each category, a clustered column chart places them in parallel: readers have to add the column heights themselves to get the total, and it is hard to see how much of the total each part takes up. A stacked chart piles the segments of one category into a single column, where the full height is the category total and each segment is one series' share, so total and composition are read at once. Absolute values versus percentages is the most common way a stacked chart changes, and each reading suits a different situation. This article uses Spire.Presentation for JavaScript to create PowerPoint presentations with stacked charts in a React project. 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.

The 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.


Create a Stacked Column Chart

To put a category's total and the make-up of its series into a single column, start the base chart as a stacked column chart: the series of one category are no longer placed side by side but piled up in turn, where the top of the column corresponds to the sum of all series and each segment to the value of one series. The chart keeps the height comparison between totals while making clear which series add up to each total.

Writing Result
slide.Shapes.AppendChart({ type: ChartType.ColumnStacked, rectangle, init }) Inserts a stacked column chart at the specified position
chart.ChartTitle.TextProperties.Text and chart.HasTitle = true Sets and shows the chart title
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the category names, series names and the value of each category
chart.Series.SeriesLabel and chart.Categories.CategoryLabels Binds the series names and the category labels
chart.Series.get_Item(i).Values Binds the value range of the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module, confirm it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Use RectangleF.FromLTRB() to set the chart rectangle, then call Shapes.AppendChart() with ChartType.ColumnStacked to insert a stacked column chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows its title.
  4. Write the category and series names through Text of ChartData.get_Item(), and write the value of each series in each category through NumberValue.
  5. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind each series' value range with Series.get_Item(i).Values; the series stack from bottom to top in the order they are bound.
  6. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from VFS and trigger the download.

The code for creating a stacked column chart is as follows:

function App() {
  // create a stacked column chart
  const createStackedColumn = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a stacked column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(80, 100, 660, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnStacked, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the three series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const laptops = [210, 240, 225, 260];
    const tablets = [140, 150, 170, 160];
    const phones = [180, 200, 190, 230];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Quarter';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Laptops';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Tablets';
    chart.ChartData.get_Item({ row: 0, column: 3 }).Text = 'Smartphones';

    // write the values of each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = laptops[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = tablets[i];
      chart.ChartData.get_Item({ row: i + 1, column: 3 }).NumberValue = phones[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'D1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });
    chart.Series.get_Item(2).Values = chart.ChartData.get_Item({ name: 'D2', endCellName: 'D5' });

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

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

  // read the generated file from VFS and trigger 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>Create a Stacked Chart in PowerPoint</h1>
      <button onClick={createStackedColumn}>Create Stacked Column Chart</button>
    </div>
  );
}

export default App;

The presentation after creating a stacked column chart:

The presentation after creating a stacked column chart


Create a 100% Stacked Column Chart

When the totals of different categories vary widely, a stacked column chart gives most of the vertical space to the largest category while the smallest category is left with a very short column, making the proportions between segments hard to compare. A 100% stacked column chart normalizes every column to 100%, so each segment keeps only its share of the category total and categories with different totals can be compared by composition side by side. Change the chart type to ChartType.Column100PercentStacked and set the value axis scale to percentages to get such a chart.

Writing Result
slide.Shapes.AppendChart({ type: ChartType.Column100PercentStacked, rectangle, init }) Inserts a 100% stacked column chart that normalizes each category to 100%
chart.PrimaryValueAxis.NumberFormat = '0%' Shows the value axis scale as percentages

The steps are:

  1. Get the Spire.Presentation WASM module, confirm it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Use RectangleF.FromLTRB() to set the chart rectangle, then call Shapes.AppendChart() with ChartType.Column100PercentStacked to insert a 100% stacked column chart.
  3. Set the chart title, then write the category names, series names and the value of each category through ChartData.get_Item().
  4. Bind the series names, category labels and value ranges with Series.SeriesLabel, Categories.CategoryLabels and Series.get_Item(i).Values.
  5. Set PrimaryValueAxis.NumberFormat to '0%', so the value axis scale shows percentages that match the normalized columns.
  6. Call Presentation.SaveToFile() to save the result file, release the presentation with Dispose(), then read the file from VFS and trigger the download.

The code for creating a 100% stacked column chart is as follows:

function App() {
  // create a 100% stacked column chart
  const createPercentStackedColumn = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a 100% stacked column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(80, 100, 660, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Column100PercentStacked, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the three series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const laptops = [210, 240, 225, 260];
    const tablets = [140, 150, 170, 160];
    const phones = [180, 200, 190, 230];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Quarter';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Laptops';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Tablets';
    chart.ChartData.get_Item({ row: 0, column: 3 }).Text = 'Smartphones';

    // write the values of each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = laptops[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = tablets[i];
      chart.ChartData.get_Item({ row: i + 1, column: 3 }).NumberValue = phones[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'D1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });
    chart.Series.get_Item(2).Values = chart.ChartData.get_Item({ name: 'D2', endCellName: 'D5' });

    // show the value axis scale as percentages
    chart.PrimaryValueAxis.NumberFormat = '0%';

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

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

  // read the generated file from VFS and trigger 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>Create a Stacked Chart in PowerPoint</h1>
      <button onClick={createPercentStackedColumn}>Create 100% Stacked Column Chart</button>
    </div>
  );
}

export default App;

The presentation after creating a 100% stacked column chart:

The presentation after creating a 100% stacked column chart


Frequently Asked Questions

Stacked column chart or clustered column chart: which should I choose

Reason: Both chart types draw the series of one category in the same place; the difference is how the series are arranged. A clustered column chart places the series side by side, which suits comparing the height of each series; a stacked column chart piles them up, which suits reading the total and the make-up of that total.

Solution: When you need to compare the values of each series, insert a clustered column chart with ChartType.ColumnClustered; when you need to highlight the total and its composition, insert a stacked column chart with ChartType.ColumnStacked. Both use the same data, so switching the view only takes a change of chart type:

const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnStacked, rectangle: rect, init: false });

How do I hide the gridlines of a stacked chart's value axis

Reason: The horizontal gridlines that are on by default cross the stacked columns, and the boundaries between segments overlap the gridlines, which looks cluttered.

Solution: Set the fill type of the value axis major gridlines to FillFormatType.None to hide the gridlines without affecting the columns themselves:

chart.PrimaryValueAxis.MajorGridTextLines.FillType = pptModule.FillFormatType.None;

How do I show the value of each segment on a stacked chart

Reason: A stacked chart only gives the height of each segment; the exact value still has to be estimated against the value axis, which is hard to read when there are many segments.

Solution: Turn on the data labels of the series explicitly, and the value of that series in each category appears next to each segment:

chart.Series.get_Item(0).DataLabels.LabelValueVisible = true;

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.

A pie chart uses the size of each slice to show how parts make up a whole. By default the slices sit tightly together as one full circle; when you want to stress one part or make the figure easier to read, you can pull the slices outward from the center to form an exploded pie chart (also called a separated or exploded pie). Dragging slices one by one in PowerPoint is slow and hard to align; generating a presentation that already contains an exploded pie chart in the browser folds that step into an automated document workflow.

This article uses Spire.Presentation for JavaScript to build a PowerPoint presentation and insert an exploded pie chart in a React project. 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.

The 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.


Create an Exploded Pie Chart

When you create an exploded pie chart, all slices are pulled outward together, which makes each boundary clearer and the whole figure more prominent. The approach is to insert a single-series pie chart, bind the data, and then set a separation distance greater than 0 on the series, so that every slice moves out along its own angle and the pie is separated evenly.

Code Result
slide.Shapes.AppendChart({ type: ChartType.Pie, rectangle, init }) Inserts a pie chart at the specified position on the slide
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the series name and the value of each category
chart.Series.SeriesLabel, chart.Categories.CategoryLabels, chart.Series.get_Item(0).Values Binds the series name, category labels, and value range
chart.Series.get_Item(0).DataPoints.Add(cdp) and point.Fill Creates a data point for each slice and fills it with a color
chart.Series.get_Item(0).Distance = 15 Separates every slice of the series outward
chart.Series.get_Item(0).DataLabels.PercentValueVisible = true Shows the percentage on each slice

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Specify the chart rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.Pie to insert a pie chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows a title.
  4. Use ChartData.get_Item() with Text to write the category names and NumberValue to write the value of each category, then bind the series name, category labels, and value range with Series.SeriesLabel, Categories.CategoryLabels, and Series.get_Item(0).Values.
  5. Loop over the values, use new ChartDataPoint() with DataPoints.Add() to create a data point for each slice, and set Fill.FillType and Fill.SolidColor.Color so the slices have different colors.
  6. Set Series.get_Item(0).Distance to a value greater than 0 (15 in the example) so all slices of the series move outward together.
  7. Set DataLabels.PercentValueVisible to true to show the percentage on each slice.
  8. 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 to create an exploded pie chart is as follows:

function App() {
  // create an exploded pie chart
  const createExplodedPieChart = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a pie chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Pie, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Sales Share by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the categories and values
    const products = ['Laptops', 'Phones', 'Tablets', 'Accessories'];
    const shares = [35, 25, 22, 18];

    // write the category names and values
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Product';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Share';
    for (let i = 0; i < products.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = products[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = shares[i];
    }

    // bind the series name, category labels and value range
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'B1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });

    // create a data point for each slice and fill it with a different color
    const colors = [
      pptModule.Color.get_RosyBrown(),
      pptModule.Color.get_LightBlue(),
      pptModule.Color.get_LightPink(),
      pptModule.Color.get_MediumPurple(),
    ];
    for (let i = 0; i < shares.length; i++) {
      const cdp = new pptModule.ChartDataPoint(chart.Series.get_Item(0));
      cdp.Index = i;
      chart.Series.get_Item(0).DataPoints.Add(cdp);

      const point = chart.Series.get_Item(0).DataPoints.get_Item(i);
      point.Fill.FillType = pptModule.FillFormatType.Solid;
      point.Fill.SolidColor.Color = colors[i];
    }

    // set the series distance so that all slices are pulled outward
    chart.Series.get_Item(0).Distance = 15;

    // show percentages on the slices
    chart.Series.get_Item(0).DataLabels.PercentValueVisible = true;

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

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

  // read the generated file from the VFS and trigger 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>Create Exploded Pie Chart in PowerPoint</h1>
      <button onClick={createExplodedPieChart}>Create Exploded Pie Chart</button>
    </div>
  );
}

export default App;

The presentation after creating an exploded pie chart:

The presentation after creating an exploded pie chart


Explode a Single Slice

To explode a single slice, emphasize only one item in the pie chart—for example the largest share—and let it break away from the circle on its own while the other slices stay in place. In this case you do not separate the whole series; instead, create a data point for each slice in the series and then set a separation distance only on the data point of the target slice, so that this slice moves out along its own angle and draws attention.

Code Result
chart.Series.get_Item(0).DataPoints.get_Item(i) Gets the slice data point at index i
chart.Series.get_Item(0).DataPoints.get_Item(i).Distance = 30 Separates only that slice outward
chart.Series.get_Item(0).Distance left at its default The other slices stay joined as a full circle

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, load the font file, create a blank presentation with new Presentation(), and get the first slide.
  2. Specify the rectangle with RectangleF.FromLTRB(), call Shapes.AppendChart() with ChartType.Pie to insert a pie chart, then write the data with ChartData.get_Item() and bind the series name, category labels, and values.
  3. Loop over the values, use new ChartDataPoint() with DataPoints.Add() to create a data point for each slice, and set Fill so the slices have different colors.
  4. Choose the index of the slice to emphasize, get its data point with DataPoints.get_Item(index), and set its Distance to a value greater than 0 (30 in the example) so only this slice moves outward.
  5. Set DataLabels.PercentValueVisible to true to show the percentage on each slice.
  6. 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 to explode a single slice is as follows:

function App() {
  // explode a single slice
  const explodeSingleSlice = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a pie chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Pie, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Sales Share by Product';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the categories and values
    const products = ['Laptops', 'Phones', 'Tablets', 'Accessories'];
    const shares = [35, 25, 22, 18];

    // write the category names and values
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Product';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Share';
    for (let i = 0; i < products.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = products[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = shares[i];
    }

    // bind the series name, category labels and value range
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'B1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });

    // create a data point for each slice and fill it with a different color
    const colors = [
      pptModule.Color.get_RosyBrown(),
      pptModule.Color.get_LightBlue(),
      pptModule.Color.get_LightPink(),
      pptModule.Color.get_MediumPurple(),
    ];
    for (let i = 0; i < shares.length; i++) {
      const cdp = new pptModule.ChartDataPoint(chart.Series.get_Item(0));
      cdp.Index = i;
      chart.Series.get_Item(0).DataPoints.Add(cdp);

      const point = chart.Series.get_Item(0).DataPoints.get_Item(i);
      point.Fill.FillType = pptModule.FillFormatType.Solid;
      point.Fill.SolidColor.Color = colors[i];
    }

    // set the distance on the slice with the largest share only, so it breaks away from the circle
    const highlightIndex = 0;
    chart.Series.get_Item(0).DataPoints.get_Item(highlightIndex).Distance = 30;

    // show percentages on the slices
    chart.Series.get_Item(0).DataLabels.PercentValueVisible = true;

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

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

  // read the generated file from the VFS and trigger 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>Create Exploded Pie Chart in PowerPoint</h1>
      <button onClick={explodeSingleSlice}>Explode a Single Slice</button>
    </div>
  );
}

export default App;

The presentation after exploding a single slice:

The presentation after exploding a single slice


FAQ

How to turn the exploded pie back into a normal pie

Cause: The separation depends on the value of Distance; when it is 0, the slices do not move outward.

Solution: Set the series distance back to 0 to restore a tightly joined pie:

chart.Series.get_Item(0).Distance = 0;

Percentages are not shown on the slices

Cause: Data labels do not show percentages by default; you need to turn that on explicitly on the series DataLabels.

Solution: Set PercentValueVisible to true, and a percentage label is drawn on each slice:

chart.Series.get_Item(0).DataLabels.PercentValueVisible = true;

All slices share the same color after exploding

Cause: A pie chart has a single series and uses one fill color by default, so the slices are not colored differently automatically.

Solution: Create a data point for each slice and set Fill per point to give each slice its own color:

const cdp = new pptModule.ChartDataPoint(chart.Series.get_Item(0));
cdp.Index = i;
chart.Series.get_Item(0).DataPoints.Add(cdp);

const point = chart.Series.get_Item(0).DataPoints.get_Item(i);
point.Fill.FillType = pptModule.FillFormatType.Solid;
point.Fill.SolidColor.Color = colors[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.

Tables in a slide deck often exist to make information comparable: a header row sits tighter while data rows get more room to breathe, a text column such as a store name needs to be wider, and numeric columns such as quantities or amounts can be narrower. When row heights and column widths are all identical, the text feels cramped in one place and the table looks empty in another; dragging each row and column by hand cannot hit exact values and has to be redone for the next table.

This article uses Spire.Presentation for JavaScript to set the row heights and column widths of PowerPoint tables 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.


Set the row height of a PowerPoint table

The rows of a table do not all play the same role: a header row should stand out, data rows should stay even, and a total row may need more breathing room. With one height for the whole table, it is hard to tell important rows from ordinary ones; dragging by hand is a matter of eyeballing and rarely gives a repeatable size. Setting heights row by row fixes the height distribution of the table, so the same proportions can be reused for different content.

Writing Result
table.TableRows.Count Gets the number of rows in the table
table.TableRows.get_Item(row).Height Gets or sets the height of the specified row

The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the font and the presentation into the VFS, create a Presentation object and load it 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. Loop over the rows up to TableRows.Count and set table.TableRows.get_Item(row).Height to the intended value.
  4. 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 code to set the row height of a PowerPoint table is as follows:

function App() {
  // set the row heights of a PowerPoint table
  const setRowHeights = 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 = 'en_TableSize.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 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;
      }
    }

    // set the height of each row in order
    const rowHeights = [100, 85, 70, 55, 40];
    for (let row = 0; row < table.TableRows.Count; row++) {
      table.TableRows.get_Item(row).Height = rowHeights[row];
    }

    // save the result file
    const outputFileName = 'SetRowHeight_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>Table Row Height and Column Width in PowerPoint</h1>
      <button onClick={setRowHeights}>Set row heights</button>
    </div>
  );
}

export default App;

Presentation after setting the table row heights:

Presentation after setting the table row heights


Set the column width of a PowerPoint table

Column width decides how much text a column can hold. A text column that is too narrow wraps, a numeric column that is too wide pushes the others to the edge, and equal widths for every column rarely suit content of very different lengths. With a width per column, text columns and numeric columns each get what they need, and the horizontal proportions of the table stay stable.

Writing Result
table.ColumnsList.Count Gets the number of columns in the table
table.ColumnsList.get_Item(col).Width Gets or sets the width of the specified column

The steps are:

  1. Get the Spire.Presentation WASM module and check that it is ready, load the font and the presentation into the VFS, create a Presentation object and load it 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. Loop over the columns up to ColumnsList.Count and set table.ColumnsList.get_Item(col).Width to the intended value.
  4. 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 code to set the column width of a PowerPoint table is as follows:

function App() {
  // set the column widths of a PowerPoint table
  const setColumnWidths = 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 = 'en_TableSize.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 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;
      }
    }

    // set the width of each column in order
    const columnWidths = [80, 130, 170, 220];
    for (let col = 0; col < table.ColumnsList.Count; col++) {
      table.ColumnsList.get_Item(col).Width = columnWidths[col];
    }

    // save the result file
    const outputFileName = 'SetColumnWidth_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>Table Row Height and Column Width in PowerPoint</h1>
      <button onClick={setColumnWidths}>Set column widths</button>
    </div>
  );
}

export default App;

Presentation after setting the table column widths:

Presentation after setting the table column widths


FAQ

How do I auto-fit table column widths to the text

Reason: Column contents differ in length. With fixed widths, text columns tend to wrap while numeric columns leave large blank areas, and trying a value per column is slow and hard to reproduce.

Solution: Call AdjustColumnByTextWidth() on each column; it recomputes the width from that column's longest text:

for (let col = 0; col < table.ColumnsList.Count; col++) {
  table.ColumnsList.get_Item(col).AdjustColumnByTextWidth();
}

Why can't I find the table when walking the shape collection

Reason: Only an editable table object is an ITable. If the table on the slide was inserted as a screenshot, picture, or embedded object, it is an ordinary picture or OLE object, and shape instanceof pptModule.ITable will never be true.

Solution: Open the deck in PowerPoint and check that the table's cells can be edited. If it is a picture, insert it again as a table, or convert it in the source document before processing.


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.

Tables are a common element for carrying structured content in a presentation, and where a table sits on the slide directly affects the balance of the layout: pinned to a page edge, centered, or lined up with other elements, each reads differently. Dragging a table into place by hand is rarely precise, and it is hard to land it exactly on the layout's center line.

This article uses Spire.Presentation for JavaScript to adjust where a PowerPoint table sits on a slide 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.

The two core features covered are:

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.


Set the horizontal alignment of a PowerPoint table

Horizontal alignment decides whether a table is pinned to the left of the slide, centered, or pinned to the right. When a table on a page must line up with the layout's center line, or sit consistently on one side, dragging it rarely gives a precise position; specifying it once with SetShapeAlignment sends the table to the matching horizontal position on the slide. The three values correspond to flush left, horizontal center, and flush right.

Code Result
table.SetShapeAlignment(ShapeAlignment.AlignLeft) The table's left edge aligns with the slide's left edge
table.SetShapeAlignment(ShapeAlignment.AlignCenter) The table is centered horizontally on the slide
table.SetShapeAlignment(ShapeAlignment.AlignRight) The table's right edge aligns with the slide's right edge

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, load the presentation into the VFS, then open it with LoadFromFile() and get the first slide.
  2. Iterate over slide.Shapes, test whether a shape is a table with shape instanceof pptModule.ITable, and get the table object.
  3. Call SetShapeAlignment() with ShapeAlignment.AlignCenter to center the table horizontally on the slide; use AlignLeft or AlignRight for the left or right edge.
  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 setting the horizontal alignment of a PowerPoint table is shown below:

function App() {
  // set the horizontal alignment of a PowerPoint table
  const alignHorizontally = 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;
    }

    // load the presentation into the VFS
    const inputFileName = 'en_TableAlignment.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

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

    // iterate over the shapes 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;
      }
    }

    // center the table horizontally on the slide (or use AlignLeft / AlignRight for the left / right edge)
    table.SetShapeAlignment(pptModule.ShapeAlignment.AlignCenter);

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

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

  // read the generated file from the VFS and trigger 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>Align PowerPoint Tables</h1>
      <button onClick={alignHorizontally}>Horizontal</button>
    </div>
  );
}

export default App;

The presentation after centering the table horizontally:

The presentation after centering the table horizontally


Set the vertical alignment of a PowerPoint table

Vertical alignment decides whether a table is pinned to the top of the slide, centered, or pinned to the bottom. When a table is shorter than the page and there is plenty of whitespace above and below, this difference is the most visible: a top-aligned table hugs the upper edge, a centered one falls in the middle, and a bottom-aligned one sits near the lower edge. It only adjusts the vertical position and leaves the table's horizontal placement untouched.

Code Result
table.SetShapeAlignment(ShapeAlignment.AlignTop) The table's top edge aligns with the slide's top edge
table.SetShapeAlignment(ShapeAlignment.AlignMiddle) The table is centered vertically on the slide
table.SetShapeAlignment(ShapeAlignment.AlignBottom) The table's bottom edge aligns with the slide's bottom edge

The steps are:

  1. Get the Spire.Presentation WASM module and confirm it is ready, load the presentation into the VFS, then open it with LoadFromFile() and get the first slide.
  2. Iterate over slide.Shapes, test whether a shape is a table with shape instanceof pptModule.ITable, and get the table object.
  3. Call SetShapeAlignment() with ShapeAlignment.AlignMiddle to center the table vertically on the slide; use AlignTop or AlignBottom for the top or bottom edge.
  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 setting the vertical alignment of a PowerPoint table is shown below:

function App() {
  // set the vertical alignment of a PowerPoint table
  const alignVertically = 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;
    }

    // load the presentation into the VFS
    const inputFileName = 'en_TableAlignment.pptx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

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

    // iterate over the shapes 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;
      }
    }

    // center the table vertically on the slide (or use AlignTop / AlignBottom for the top / bottom edge)
    table.SetShapeAlignment(pptModule.ShapeAlignment.AlignMiddle);

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

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

  // read the generated file from the VFS and trigger 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>Align PowerPoint Tables</h1>
      <button onClick={alignVertically}>Vertical</button>
    </div>
  );
}

export default App;

The presentation after centering the table vertically:

The presentation after centering the table vertically


FAQ

How to center a table both horizontally and vertically on the slide

Cause: SetShapeAlignment adjusts only one direction per call — AlignCenter handles horizontal centering and AlignMiddle handles vertical centering — so a single call cannot do both at once.

Resolution: Call AlignCenter and then AlignMiddle on the same table; the two settings stack and the table lands in the center of the slide:

table.SetShapeAlignment(pptModule.ShapeAlignment.AlignCenter);
table.SetShapeAlignment(pptModule.ShapeAlignment.AlignMiddle);

How to place a table at an arbitrary coordinate

Cause: SetShapeAlignment only offers relative positions such as edge and center, and cannot target an arbitrary precise coordinate.

Resolution: Assign point values directly to table.Left and table.Top to place the table at a specified position on the slide, for example:

table.Left = 200;
table.Top = 120;

Does alignment, which only changes position, affect the text and style inside the table

Cause: SetShapeAlignment adjusts the position of the table as a whole on the slide, and acts on the shape itself.

Resolution: A table's cell text, fonts, fills and borders are not affected by the alignment operation, and the cell text stays the same before and after; to adjust the content or formatting as well, set the cell properties separately.


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.

Charts turn a set of numbers into a shape you can read at a glance, making proportions, trends, and comparisons in a presentation far easier to grasp. Inserting a chart by hand in PowerPoint means picking a type, pasting the data, and adjusting titles and labels each time; generating a presentation that already contains charts in the browser folds that step into an automated document workflow.

This article uses Spire.Presentation for JavaScript to build PowerPoint presentations and add charts in a React project. 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. The product supports many chart types, including column, line, pie, bar, scatter, and bubble charts; this tutorial selects three common types—column, pie, and line—as examples.

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


Create a Column Chart

A column chart is a good fit for comparing several series across multiple categories: each category gets a group of columns of different heights, so the differences stand out at once. To build one, write the values for each category into the chart's data table, bind a data range to each series, and Spire.Presentation draws the columns on the slide.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.ColumnClustered, rectangle, init }) Inserts a clustered column chart at the given position on the slide
chart.ChartTitle.TextProperties.Text and chart.HasTitle = true Sets and shows the chart title
chart.ChartData.get_Item({ row, column }).Text Writes the series names and category names
chart.ChartData.get_Item({ row, column }).NumberValue Writes the value for each category
chart.Series.SeriesLabel Specifies the range that holds the series names
chart.Categories.CategoryLabels Specifies the range that holds the category labels
chart.Series.get_Item(i).Values Binds the value range to the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.ColumnClustered to insert a clustered column chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows a title.
  4. Write the series names and category names through ChartData.get_Item() with Text, and the values for each category with NumberValue.
  5. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind a value range to each series with Series.get_Item(i).Values.
  6. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a column chart is as follows:

function App() {
  // create a column chart
  const createColumnChart = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a clustered column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnClustered, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data for two series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const online = [128, 156, 142, 180];
    const inStore = [96, 88, 110, 124];

    // write the series names
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Online';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'In-store';

    // write the category names and the value for each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = online[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = inStore[i];
    }

    // bind the series names, category labels, and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });

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

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

  // read the generated file from the VFS and trigger 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>Create Charts in PowerPoint</h1>
      <button onClick={createColumnChart}>Create a column chart</button>
    </div>
  );
}

export default App;

The presentation after creating a column chart:

The presentation after creating a column chart


Create a Pie Chart

A pie chart uses the size of each slice to show how each part contributes to the whole, which suits category data with only one set of values. Beyond inserting the shape, you can give every slice its own color and let the labels show both the value and the percentage, making the composition clearer.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.Pie, rectangle, init }) Inserts a pie chart at the given position on the slide
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the categories and values of the single series
chart.Series.get_Item(i).DataPoints.Add(cdp) Creates a data point for each slice
point.Fill.FillType = FillFormatType.Solid and point.Fill.SolidColor.Color Fills each slice with a specific solid color
chart.Series.get_Item(i).DataLabels.LabelValueVisible Shows the value on each slice
chart.Series.get_Item(i).DataLabels.PercentValueVisible Shows the percentage on each slice

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.Pie to insert a pie chart.
  3. Set the chart title, then write the category names, series name, and values through ChartData.get_Item().
  4. Bind the series name, category labels, and value range with Series.SeriesLabel, Categories.CategoryLabels, and Series.get_Item(0).Values.
  5. Loop over the values, create a data point for each slice with new ChartDataPoint() and DataPoints.Add(), then set Fill.FillType and Fill.SolidColor.Color so the slices differ in color.
  6. Set DataLabels.LabelValueVisible and DataLabels.PercentValueVisible to true to show the value and the percentage.
  7. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a pie chart is as follows:

function App() {
  // create a pie chart
  const createPieChart = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a pie chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.Pie, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Sales Share by Region';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the categories and values
    const regions = ['Northeast', 'South', 'West', 'Midwest'];
    const shares = [35, 25, 22, 18];

    // write the category names and values
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Region';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Share';
    for (let i = 0; i < regions.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = regions[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = shares[i];
    }

    // bind the series name, category labels, and value range
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'B1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });

    // create a data point for each slice and fill it with a different color
    const colors = [
      pptModule.Color.get_RosyBrown(),
      pptModule.Color.get_LightBlue(),
      pptModule.Color.get_LightPink(),
      pptModule.Color.get_MediumPurple(),
    ];
    for (let i = 0; i < shares.length; i++) {
      const cdp = new pptModule.ChartDataPoint(chart.Series.get_Item(0));
      cdp.Index = i;
      chart.Series.get_Item(0).DataPoints.Add(cdp);

      const point = chart.Series.get_Item(0).DataPoints.get_Item(i);
      point.Fill.FillType = pptModule.FillFormatType.Solid;
      point.Fill.SolidColor.Color = colors[i];
    }

    // show the value and the percentage on each slice
    chart.Series.get_Item(0).DataLabels.LabelValueVisible = true;
    chart.Series.get_Item(0).DataLabels.PercentValueVisible = true;

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

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

  // read the generated file from the VFS and trigger 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>Create Charts in PowerPoint</h1>
      <button onClick={createPieChart}>Create a pie chart</button>
    </div>
  );
}

export default App;

The presentation after creating a pie chart:

The presentation after creating a pie chart


Create a Line Chart

A line chart connects the values of one series across categories into a single line, which makes the direction of change easy to follow. A line chart with markers also draws a point at every value, so the turning points stand out and each value can be read one by one.

Syntax What it does
slide.Shapes.AppendChart({ type: ChartType.LineMarkers, rectangle, init }) Inserts a line chart with data markers at the given position on the slide
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the series names, category names, and values
chart.Series.SeriesLabel and chart.Categories.CategoryLabels Binds the series names and category labels
chart.Series.get_Item(i).Values Binds the value range to the i-th series

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.LineMarkers to insert a line chart with data markers.
  3. Set the chart title, then write the series names, category names, and values through ChartData.get_Item().
  4. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind a value range to each series with Series.get_Item(i).Values.
  5. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a line chart is as follows:

function App() {
  // create a line chart
  const createLineChart = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a line chart with data markers on the slide
    const rect = pptModule.RectangleF.FromLTRB(90, 100, 640, 420);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.LineMarkers, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Quarterly Sales Trend';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data for two series
    const quarters = ['Q1', 'Q2', 'Q3', 'Q4'];
    const online = [128, 156, 142, 180];
    const inStore = [96, 88, 110, 124];

    // write the series names
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Online';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'In-store';

    // write the category names and the value for each category
    for (let i = 0; i < quarters.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = quarters[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = online[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = inStore[i];
    }

    // bind the series names, category labels, and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A5' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B5' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C5' });

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

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

  // read the generated file from the VFS and trigger 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>Create Charts in PowerPoint</h1>
      <button onClick={createLineChart}>Create a line chart</button>
    </div>
  );
}

export default App;

The presentation after creating a line chart:

The presentation after creating a line chart


FAQ

Why is the chart title not shown after I set it

Cause: Assigning ChartTitle.TextProperties.Text alone is not enough; when the title switch is off, the title is not drawn.

Solution: Set chart.HasTitle to true at the same time as the text, and the title appears above the chart:

chart.ChartTitle.TextProperties.Text = 'Quarterly Sales';
chart.HasTitle = true;

Why do the category labels or values show up empty

Cause: After the chart data is written, the chart has no categories or values to use until the category label range and each series' value range are bound to it.

Solution: Write the cells with ChartData.get_Item() first, then bind the matching ranges with Categories.CategoryLabels and Series.get_Item(i).Values; both use ChartData.get_Item({ name, endCellName }) to give the start and end cells.

How do I create a line chart with data markers

Cause: There are several line chart types; a plain line chart only draws the line, so the marker type has to be chosen explicitly.

Solution: When calling Shapes.AppendChart(), set the type to ChartType.LineMarkers, and a data marker is drawn at every value.


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.

A chart that carries only one chart type forces data with different magnitudes or different readings onto separate slides, and readers have to compare across two charts. A combination chart merges two or more chart types into a single chart: each series gets its own type while the shared category axis keeps the series aligned, so highs and trends can be read together. Which types to pair is decided by the questions the chart has to answer at once; there is no fixed pairing, and columns plus a line are simply the most common in practice. This article uses Spire.Presentation for JavaScript to create PowerPoint presentations with combination charts in a React project. 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.

The 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.


Create a Column and Line Combination Chart

A chart with a single type gives data of different magnitudes or readings one slide each, and comparing them first requires aligning two category axes. A combination chart starts from a base chart and changes the type of one series to another chart type, so both readings land in a single chart whose category axis is already aligned. This feature is the foundation of a combination chart: once a column and a line coexist, the same data is expressed in two chart types, and how the scales are assigned can be adjusted in the next step.

Writing Result
slide.Shapes.AppendChart({ type: ChartType.ColumnClustered, rectangle, init }) Inserts a clustered column chart at the specified position on the slide
chart.ChartTitle.TextProperties.Text and chart.HasTitle = true Sets and shows the chart title
chart.ChartData.get_Item({ row, column }).Text / NumberValue Writes the category names, series names, and the values of each category
chart.Series.SeriesLabel and chart.Categories.CategoryLabels Binds the ranges that hold the series names and category labels
chart.Series.get_Item(i).Values Binds the value range of the i-th series
chart.Series.get_Item(i).Type = ChartType.LineMarkers Changes the type of the specified series to a line with data markers

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.ColumnClustered to insert a clustered column chart.
  3. Set ChartTitle.TextProperties.Text and set HasTitle to true so the chart shows a title.
  4. Write the category names and series names through ChartData.get_Item() with Text, and the values for each category with NumberValue.
  5. Bind the series names and category labels with Series.SeriesLabel and Categories.CategoryLabels, then bind a value range to each series with Series.get_Item(i).Values.
  6. Set the Type of the second series to ChartType.LineMarkers, so that series turns from a column into a line with data markers and forms a combination chart with the first series.
  7. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for creating a combination chart is as follows:

function App() {
  // create a column and line combination chart
  const createCombinationChart = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a clustered column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(60, 90, 700, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnClustered, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Monthly Sales and Growth Rate';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the two series
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    const sales = [200, 250, 300, 150, 200, 400];
    const growth = [0.6, 0.8, 0.6, 0.2, 0.5, 0.9];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Month';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Sales';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Growth';

    // write the values of each category
    for (let i = 0; i < months.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = months[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = sales[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = growth[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A7' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B7' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C7' });

    // change the type of the second series to a line with markers, forming a combination chart with the column
    chart.Series.get_Item(1).Type = pptModule.ChartType.LineMarkers;

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

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

  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>Create a Combination Chart in PowerPoint</h1>
      <button onClick={createCombinationChart}>Create Combination Chart</button>
    </div>
  );
}

export default App;

The presentation after creating a column and line combination chart:

The presentation after creating a column and line combination chart


Plot a Series on the Secondary Axis

In a combination chart, when two series share one value axis and their magnitudes differ widely, the smaller series is pressed into a line hugging the bottom of the chart, and its movement cannot be read. The secondary axis gives such a series its own value scale on the right: the column still follows the left scale while the line follows the right one, so both magnitudes can fill the vertical space of the chart. The right axis can also use its own number format, so the scale shows the unit it needs directly.

Writing Result
chart.Series.get_Item(i).UseSecondAxis = true Plots the specified series on the secondary axis
chart.SecondaryValueAxis.NumberFormat Sets the number format of the secondary axis scale
chart.SecondaryValueAxis.MajorGridTextLines.FillType = FillFormatType.None Hides the gridlines of the secondary axis

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the font file, then create a blank presentation with new Presentation() and get the first slide.
  2. Define the chart's rectangle with RectangleF.FromLTRB(), then call Shapes.AppendChart() with ChartType.ColumnClustered to insert a clustered column chart.
  3. Set the chart title, then write the category names, series names, and the values of each category through ChartData.get_Item().
  4. Bind the series names, category labels, and value ranges with Series.SeriesLabel, Categories.CategoryLabels, and Series.get_Item(i).Values, and set the Type of the second series to ChartType.LineMarkers.
  5. Set the UseSecondAxis of that series to true, so the line takes its scale from the secondary axis.
  6. Set SecondaryValueAxis.NumberFormat to the number format you need, and set SecondaryValueAxis.MajorGridTextLines.FillType to FillFormatType.None to hide the gridlines of the secondary axis.
  7. Save the result file with Presentation.SaveToFile(), release the presentation with Dispose(), then read the file back from the VFS and trigger the download.

The code for plotting a series on the secondary axis is as follows:

function App() {
  // plot a series on the secondary axis
  const plotOnSecondaryAxis = 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;
    }

    // load the font so that the text in the chart renders correctly
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // create a blank presentation and get the first slide
    const ppt = new pptModule.Presentation();
    const slide = ppt.Slides.get_Item(0);

    // insert a clustered column chart on the slide
    const rect = pptModule.RectangleF.FromLTRB(60, 90, 700, 430);
    const chart = slide.Shapes.AppendChart({ type: pptModule.ChartType.ColumnClustered, rectangle: rect, init: false });

    // set the chart title
    chart.ChartTitle.TextProperties.Text = 'Monthly Sales and Growth Rate';
    chart.ChartTitle.TextProperties.IsCentered = true;
    chart.ChartTitle.Height = 30;
    chart.HasTitle = true;

    // prepare the data of the two series
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'];
    const sales = [200, 250, 300, 150, 200, 400];
    const growth = [0.6, 0.8, 0.6, 0.2, 0.5, 0.9];

    // write the category and series names
    chart.ChartData.get_Item({ row: 0, column: 0 }).Text = 'Month';
    chart.ChartData.get_Item({ row: 0, column: 1 }).Text = 'Sales';
    chart.ChartData.get_Item({ row: 0, column: 2 }).Text = 'Growth';

    // write the values of each category
    for (let i = 0; i < months.length; i++) {
      chart.ChartData.get_Item({ row: i + 1, column: 0 }).Text = months[i];
      chart.ChartData.get_Item({ row: i + 1, column: 1 }).NumberValue = sales[i];
      chart.ChartData.get_Item({ row: i + 1, column: 2 }).NumberValue = growth[i];
    }

    // bind the series names, category labels and value ranges
    chart.Series.SeriesLabel = chart.ChartData.get_Item({ name: 'B1', endCellName: 'C1' });
    chart.Categories.CategoryLabels = chart.ChartData.get_Item({ name: 'A2', endCellName: 'A7' });
    chart.Series.get_Item(0).Values = chart.ChartData.get_Item({ name: 'B2', endCellName: 'B7' });
    chart.Series.get_Item(1).Values = chart.ChartData.get_Item({ name: 'C2', endCellName: 'C7' });

    // change the second series to a line with markers
    chart.Series.get_Item(1).Type = pptModule.ChartType.LineMarkers;

    // plot the line series on the secondary axis
    chart.Series.get_Item(1).UseSecondAxis = true;

    // show the secondary axis scale as percentages and hide its gridlines
    chart.SecondaryValueAxis.NumberFormat = '0%';
    chart.SecondaryValueAxis.MajorGridTextLines.FillType = pptModule.FillFormatType.None;

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

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

  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>Create a Combination Chart in PowerPoint</h1>
      <button onClick={plotOnSecondaryAxis}>Use Secondary Axis</button>
    </div>
  );
}

export default App;

The presentation after plotting a series on the secondary axis:

The presentation after plotting a series on the secondary axis


FAQ

How to fix the scale range of the secondary axis

Cause: The upper and lower limits of the secondary axis are calculated automatically by default, so they change whenever the data changes. In a report that contains several charts, inconsistent right-hand scales make the charts hard to compare side by side.

Solution: Set IsAutoMax and IsAutoMin to false to turn off the automatic calculation, then give MinValue and MaxValue fixed limits:

chart.SecondaryValueAxis.IsAutoMax = false;
chart.SecondaryValueAxis.IsAutoMin = false;
chart.SecondaryValueAxis.MinValue = 0;
chart.SecondaryValueAxis.MaxValue = 1;

How to hide the legend or move it below the chart

Cause: The legend is shown on the right of the chart by default, and with many categories or series it takes width away from the plot area; with only one or two series, the legend is often redundant.

Solution: Set HasLegend to false to hide the legend. To keep the legend but change its position, use ChartLegend.Position, for example to place it below the chart:

chart.HasLegend = false;

chart.HasLegend = true;
chart.ChartLegend.Position = pptModule.ChartLegendPositionType.Bottom;

How to show the value of each point on the line

Cause: A line only shows the trend, so individual values have to be estimated against the right-hand scale; in a combination chart the two series use axes with different scales, which makes the readings easier to mix up.

Solution: Set DataLabels.LabelValueVisible of the line series to true, and the value of each data point is shown next to the point:

chart.Series.get_Item(1).DataLabels.LabelValueVisible = true;

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.

Tables are a common way to present structured content on a slide, and where the text sits inside a cell directly affects readability: body columns are usually left aligned, numeric columns right aligned, and header rows centered, while each column is also nudged up or down to suit its content. Adjusting every cell by hand becomes hard to keep consistent once a table grows, and the same work repeats for the next deck.

This article uses Spire.Presentation for JavaScript to set the text alignment of PowerPoint tables 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 three 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.


Set the Horizontal Alignment of Table Text

Horizontal alignment decides whether text sits at the left, center or right of a cell, or is stretched across the full width. Columns that hold different kinds of content often need different positions, and assigning them column by column lines similar items up along one vertical edge while separating values from labels. It is set paragraph by paragraph, so changing one column leaves the others untouched.

Syntax Result
paragraph.Alignment = TextAlignmentType.Left Aligns the paragraph text to the left of the cell
paragraph.Alignment = TextAlignmentType.Center Centers the paragraph text horizontally in the cell
paragraph.Alignment = TextAlignmentType.Right Aligns the paragraph text to the right of the cell
paragraph.Alignment = TextAlignmentType.Justify Justifies the paragraph text, spreading spacing to fill the line

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the presentation into the VFS, then open it with LoadFromFile() and get the first slide.
  2. Walk slide.Shapes and use shape instanceof pptModule.ITable to tell whether a shape is a table, and keep the table object.
  3. Loop over the columns of one data row, take TextFrame.Paragraphs.get_Item(0) of each cell, and set Alignment to TextAlignmentType.Left, Center, Right and Justify in turn.
  4. 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 sets the horizontal alignment of table text:

function App() {
  const setHorizontalAlignment = 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 = 'en_TextAlignment.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 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;
      }
    }

    // set the horizontal alignment of the first data row column by column
    const alignments = [
      pptModule.TextAlignmentType.Left,
      pptModule.TextAlignmentType.Center,
      pptModule.TextAlignmentType.Right,
      pptModule.TextAlignmentType.Justify,
    ];
    for (let col = 1; col <= 4; col++) {
      table.get_Item(col, 1).TextFrame.Paragraphs.get_Item(0).Alignment = alignments[col - 1];
    }

    // save the result file
    const outputFileName = 'HorizontalAlignment_result.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>Text Alignment in PowerPoint Tables</h1>
      <button onClick={setHorizontalAlignment}>Horizontal</button>
    </div>
  );
}

export default App;

The presentation after setting the horizontal alignment of the first data row:

The presentation after setting the horizontal alignment of the first data row


Set the Vertical Alignment of Table Text

Vertical alignment decides whether text hugs the top of a cell, sits in the middle or drops to the bottom. It shows most clearly when the row is taller than the text: short text at the top sticks to the upper edge, centered text lands in the middle, and bottom-aligned text approaches the lower edge. It is set at the cell level and is independent of the paragraph-level horizontal alignment.

Syntax Result
cell.TextAnchorType = TextAnchorType.Top Aligns the cell text to the top
cell.TextAnchorType = TextAnchorType.Center Centers the cell text vertically
cell.TextAnchorType = TextAnchorType.Bottom Aligns the cell text to the bottom

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the presentation into the VFS, then open it with LoadFromFile() and get the first slide.
  2. Walk slide.Shapes and use shape instanceof pptModule.ITable to tell whether a shape is a table, and keep the table object.
  3. Loop over the columns of one data row and set each cell's TextAnchorType to TextAnchorType.Top, Center and Bottom in turn.
  4. 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 sets the vertical alignment of table text:

function App() {
  const setVerticalAlignment = 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 = 'en_TextAlignment.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 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;
      }
    }

    // set the vertical alignment of the second data row column by column
    const anchors = [
      pptModule.TextAnchorType.Top,
      pptModule.TextAnchorType.Center,
      pptModule.TextAnchorType.Bottom,
    ];
    for (let col = 1; col <= 3; col++) {
      table.get_Item(col, 2).TextAnchorType = anchors[col - 1];
    }

    // save the result file
    const outputFileName = 'VerticalAlignment_result.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>Text Alignment in PowerPoint Tables</h1>
      <button onClick={setVerticalAlignment}>Vertical</button>
    </div>
  );
}

export default App;

The presentation after setting the vertical alignment of the second data row:

The presentation after setting the vertical alignment of the second data row


Set Both Horizontal and Vertical Alignment

In real layouts the horizontal and vertical positions are often decided together: a label at the top-left, emphasis text in the exact center, or a value at the bottom-right are all results of combining the two. Horizontal alignment lives on the paragraph and vertical alignment on the cell, so assigning both gives the combined effect; setting them cell by cell lets each column of the same table use a different arrangement.

Syntax Result
paragraph.Alignment = TextAlignmentType.Left and cell.TextAnchorType = TextAnchorType.Top Text aligned to the top-left
paragraph.Alignment = TextAlignmentType.Center and cell.TextAnchorType = TextAnchorType.Center Text centered both horizontally and vertically
paragraph.Alignment = TextAlignmentType.Right and cell.TextAnchorType = TextAnchorType.Bottom Text aligned to the bottom-right
paragraph.Alignment = TextAlignmentType.Justify and cell.TextAnchorType = TextAnchorType.Center Text justified and vertically centered

The steps are:

  1. Get the Spire.Presentation WASM module and make sure it is ready, load the presentation into the VFS, then open it with LoadFromFile() and get the first slide.
  2. Walk slide.Shapes and use shape instanceof pptModule.ITable to tell whether a shape is a table, and keep the table object.
  3. For every cell of that row assign both at once: set TextFrame.Paragraphs.get_Item(0).Alignment to a TextAlignmentType value and TextAnchorType to a TextAnchorType value, pairing them.
  4. 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 sets both the horizontal and vertical alignment of table text:

function App() {
  const setBothAlignments = 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 = 'en_TextAlignment.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 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;
      }
    }

    // set the horizontal and the vertical alignment of every cell in the third data row
    table.get_Item(1, 3).TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Left;
    table.get_Item(1, 3).TextAnchorType = pptModule.TextAnchorType.Top;

    table.get_Item(2, 3).TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Center;
    table.get_Item(2, 3).TextAnchorType = pptModule.TextAnchorType.Center;

    table.get_Item(3, 3).TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Right;
    table.get_Item(3, 3).TextAnchorType = pptModule.TextAnchorType.Bottom;

    table.get_Item(4, 3).TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Justify;
    table.get_Item(4, 3).TextAnchorType = pptModule.TextAnchorType.Center;

    // save the result file
    const outputFileName = 'BothAlignments_result.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>Text Alignment in PowerPoint Tables</h1>
      <button onClick={setBothAlignments}>Combined</button>
    </div>
  );
}

export default App;

The presentation after setting both the horizontal and vertical alignment:

The presentation after setting both the horizontal and vertical alignment


FAQ

How do I align a cell that holds several paragraphs

Reason: Alignment belongs to a paragraph, not a cell. When a cell holds more than one paragraph, setting only the first one leaves the others unchanged.

Solution: Read TextFrame.Paragraphs.Count first, then set Alignment on each paragraph by index:

const paragraphs = cell.TextFrame.Paragraphs;
for (let p = 0; p < paragraphs.Count; p++) {
  paragraphs.get_Item(p).Alignment = pptModule.TextAlignmentType.Center;
}

How do I align a merged cell

Reason: Once cells are merged, several positions in the merged area actually point to the same cell, so setting each one repeats the work; to change the alignment you only need to target the merged cell itself.

Solution: A merged cell can be located through FirstRowIndex and FirstColumnIndex, or taken directly with table.get_Item() using the anchor position at the top-left of the merged area; set its TextFrame.Paragraphs.get_Item(0).Alignment and TextAnchorType, and after saving, positions covered by the merge still read back the same cell with the alignment kept:

const merged = table.get_Item(column, row); // column and row are the top-left of the merged area
merged.TextFrame.Paragraphs.get_Item(0).Alignment = pptModule.TextAlignmentType.Center;
merged.TextAnchorType = pptModule.TextAnchorType.Center;

Why does nothing change after setting Justify alignment

Reason: TextAlignmentType.Justify stretches every line except the last. When the cell text is a single line, or already nearly fills the line, there is no spare space to stretch, so it looks almost the same as the default alignment.

Solution: To see the justify effect, let the cell text wrap onto several lines and narrow the column a little so the inner lines have gaps to stretch; if only the left-to-right position of a single line matters, TextAlignmentType.Left, Center or Right is more direct.


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.

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.

Page 1 of 25
page 1