JavaScript (51)
Adding or removing text boxes in Word is a valuable skill that enhances document layout and visual appeal. Text boxes provide a flexible way to highlight important information, create side notes, or organize content more effectively. They allow for creative formatting options, enabling you to draw attention to specific areas of your document.
In this article, you will learn how to add or move text boxes in a Word document in React using Spire.Doc for JavaScript.
Install Spire.Doc for JavaScript
To get started wtih manipulating text boxes in Word in a React applicaiton, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Add a Text Box to a Word Document in React
Spire.Doc for JavaScript offers the Paragraph.AppendTextBox() method to seamlessly insert a text box into a specified paragraph. Once inserted, you can customize the text box by adding content and applying formatting using properties like TextBox.Body and TextBox.Format.
The following are the steps to add a text box to a Word document in React:
- Load required font and input file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Access the first section and paragraph.
- Insert a text box to the paragraph using the Paragraph.AppendTextBox() method.
- Add a paragraph to the text box and append text to it through the TextBox.Body property.
- Customize the appearance of the text box through the TextBox.Format property.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Doc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to add text box
const AddTextBox = async () => {
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// load the input file and add it to the VFS
const inputFileName = 'input.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Get a specific section
let section = doc.Sections.get_Item(0)
// Get a specific paragraph
let paragraph = section.Paragraphs.get_Item(0)
// Insert a textbox and set its wrapping style
let textBox = paragraph.AppendTextBox(150, 100);
textBox.Format.TextWrappingStyle = wasmModule.TextWrappingStyle.Square;
// Set the position of the textbox
textBox.Format.HorizontalPosition = 0;
textBox.Format.VerticalPosition = 50;
// Set the line style and fill color
textBox.Format.LineColor = wasmModule.Color.get_DarkBlue();
textBox.Format.LineStyle = wasmModule.TextBoxLineStyle.Simple;
textBox.Format.FillColor = wasmModule.Color.get_LightGray();
// Add a paragraph to the textbox
let para = textBox.Body.AddParagraph();
let textRange = para.AppendText("This is a sample text box created by Spire.Doc for JavaScript.");
// Format the text
textRange.CharacterFormat.FontName = "Arial";
textRange.CharacterFormat.FontSize = 15;
textRange.CharacterFormat.TextColor = wasmModule.Color.get_Blue();
// Set the horizontal alignment of the paragraph
para.Format.HorizontalAlignment = wasmModule.HorizontalAlignment.Center;
// Define the output file name
const outputFileName = "Textbox.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Add a text box to Word in React</h1>
<button onClick={AddTextBox} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

Here is a screenshot of the generated Word file that includes a text box:

Remove a Text Box from a Word Document in React
Spire.Doc for JavaScript includes the Document.TextBoxes.RemoveAt() method, which allows you to delete a specific text box by its index. If you need to remove all text boxes from a Word document, you can use the Document.TextBoxes.Clear() method for a quick and efficient solution.
The following are the steps to remove a text box from a Word document in React:
- Load the input file into the virtual file system (VFS).
- Create a Document object using the wasmModule.Document.Create() method.
- Load the Word file using the Document.LoadFromFile() method.
- Remove a specific text box using the Document.TextBoxes.RemoveAt() method.
- Save the document and trigger a download.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Doc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to remove text box
const RemoveTextBox = async () => {
if (wasmModule) {
// load the input file and add it to the VFS
const inputFileName = 'Textbox.docx';
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create a new document
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile(inputFileName);
// Remove the text box at index 0
doc.TextBoxes.RemoveAt(0);
// Remove all text boxes
// doc.TextBoxes.Clear();
// Define the output file name
const outputFileName = "RemoveTextBox.docx";
// Save the document to the specified path
doc.SaveToFile({fileName: outputFileName,fileFormat: wasmModule.FileFormat.Docx2013});
// Read the generated file from VFS
const fileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the file
const blob = new Blob([fileArray], {type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
doc.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Remove a text box from Word in React</h1>
<button onClick={RemoveTextBox} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Save Excel Charts and Shapes as Images with JavaScript in React
2025-02-28 00:57:01 Written by KoohjiExport Excel charts and shapes as standalone images is a critical feature for enhancing data visualization workflows. Converting charts and shapes into image formats enables seamless integration of dynamic data into reports, dashboards, or presentations, ensuring compatibility across platforms where Excel files might not be natively supported. By programmatically generating images from Excel charts and shapes within web applications using Spire.XLS for JavaScript API, developers can automate export workflows, ensure consistent visualization, and deliver dynamically updated visuals to end-users without extra manual processing steps.
In this article, we will explore how to use Spire.XLS for Java Script to save charts and shapes in Excel workbooks as images using JavaScript in React applications.
Install Spire.XLS for JavaScript
To get started with saving Excel charts and shapes as images in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:
npm i spire.xls
After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project
Save Excel Charts to Images with JavaScript
By processing Excel files using the Spire.XLS WebAssembly module, we can utilize the Workbook.SaveChartAsImage() method to save a specific chart from an Excel worksheet as an image and store it in the virtual file system (VFS). The saved image can then be downloaded or used for further processing.
The detailed steps are as follows:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Fetch the Excel file and font files into the VFS using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance using the wasmModule.Workbook.Create() method.
- Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
- Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
- Iterate though the charts and save them as images using the Workbook.SaveChartAsImage() method, specifying the worksheet and chart index as parameters.
- Save the images to the VFS using the image.Save() method.
- Download the images or use them as needed.
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirexls from the global window object
const { Module, spirexls } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirexls);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert charts to images
const SaveExcelChartAsImage = async () => {
if (wasmModule) {
// Specify the input file name
const inputFileName = 'Sample62.xlsx';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file and add it to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create the image folder in the VFS
const imageFolderName = `Images`;
wasmModule.FS.mkdir(imageFolderName, 0x1FF);
// Create an instance of the Workbook class
const workbook = wasmModule.Workbook.Create();
// Load the Excel workbook from the input file
workbook.LoadFromFile({ fileName: inputFileName });
// Iterate through each worksheet in the workbook
for (let i = 0; i < workbook.Worksheets.Count; i++) {
// Get the current worksheet
const sheet = workbook.Worksheets.get(i);
// Iterate through each chart in the worksheet
for (let j = 0; j < sheet.Charts.Count; j++) {
// Save the current chart to an image
let image = workbook.SaveChartAsImage({ worksheet: sheet, chartIndex: j})
// Save the image to the VFS
const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
image.Save(`${imageFolderName}/${cleanSheetName}_Chart-${j}.png`, 0x1FF)
}
}
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Pack the image folder to a zip file
const zip = new JSZip();
addFilesToZip(imageFolderName, zip);
// Generate a Blob from the result zip file and trigger a download
zip.generateAsync({type:"blob"})
.then(function(content) {
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = 'Charts.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}).catch(function(err) {
console.error("There was an error generating the zip file:", err);
});
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Save Excel Charts as Images Using JavaScript in React</h1>
<button onClick={SaveExcelChartAsImage} disabled={!wasmModule}>
Export Charts
</button>
</div>
);
}
export default App;

Save Excel Shapes to Images with JavaScript
We can retrieve shapes from an Excel worksheet using the Worksheet.PrstGeomShapes.get() method and save them as images using the shape.SaveToImage() method. The images can then be stored in the virtual file system (VFS) and downloaded or used for further processing.
Below are the detailed steps:
- Load the Spire.Xls.Base.js file to initialize the WebAssembly module.
- Fetch the Excel file and font files into the VFS using the wasmModule.FetchFileToVFS() method.
- Create a Workbook instance using the wasmModule.Workbook.Create() method.
- Load the Excel file into the Workbook instance using the Workbook.LoadFromFile() method.
- Retrieve a specific worksheet or iterate through all worksheets using the Workbook.Worksheets.get() method.
- Get a shape from the worksheet or iterate through all shapes using the Worksheet.PrstGeomShapes.get() method.
- Save the shapes as images using the shape.SaveToImage() method.
- Save the images to the VFS using the image.Save() method.
- Download the images or use them as needed.
- JavaScript
import React, { useState, useEffect } from 'react';
import JSZip from 'jszip';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirexls from the global window object
const { Module, spirexls } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirexls);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert shapes to images
const SaveExcelShapeAsImage = async () => {
if (wasmModule) {
// Specify the input file name
const inputFileName = 'Sample62.xlsx';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Fetch the font file and add it to the VFS
await wasmModule.FetchFileToVFS('Calibri.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
await wasmModule.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create the image folder in the VFS
const imageFolderName = `Images`;
wasmModule.FS.mkdir(imageFolderName, 0x1FF);
// Create an instance of the Workbook class
const workbook = wasmModule.Workbook.Create();
// Load the Excel workbook from the input file
workbook.LoadFromFile({ fileName: inputFileName });
// Iterate through each worksheet in the workbook
for (let i = 0; i < workbook.Worksheets.Count; i++) {
// Get the current worksheet
const sheet = workbook.Worksheets.get(i);
// Iterate through each shape in the worksheet
for (let j = 0; j < sheet.PrstGeomShapes.Count; j++) {
// Get the current shape
const shape = sheet.PrstGeomShapes.get(j);
// Save the shape to an image
const image = shape.SaveToImage();
// Save the image to the VFS
const cleanSheetName = sheet.Name.replace(/[^\w\s]/gi, '');
image.Save(`${imageFolderName}/${cleanSheetName}_Shape-${j}.png`, 0x1FF)
}
}
// Recursive function to add a directory and its contents to the ZIP
const addFilesToZip = (folderPath, zipFolder) => {
const items = wasmModule.FS.readdir(folderPath);
items.filter(item => item !== "." && item !== "..").forEach((item) => {
const itemPath = `${folderPath}/${item}`;
try {
// Attempt to read file data
const fileData = wasmModule.FS.readFile(itemPath);
zipFolder.file(item, fileData);
} catch (error) {
if (error.code === 'EISDIR') {
// If it's a directory, create a new folder in the ZIP and recurse into it
const zipSubFolder = zipFolder.folder(item);
addFilesToZip(itemPath, zipSubFolder);
} else {
// Handle other errors
console.error(`Error processing ${itemPath}:`, error);
}
}
});
};
// Pack the image folder to a zip file
const zip = new JSZip();
addFilesToZip(imageFolderName, zip);
// Generate a Blob from the result zip file and trigger a download
zip.generateAsync({type:"blob"})
.then(function(content) {
const link = document.createElement('a');
link.href = URL.createObjectURL(content);
link.download = 'Shapes.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
}).catch(function(err) {
console.error("There was an error generating the zip file:", err);
});
}
};
return (
<div style="{{">
<h1>Save Excel Shapes as Images Using JavaScript in React</h1>
<button onClick={SaveExcelShapeAsImage} disabled={!wasmModule}>
Export Shapes
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Protect or Unprotect PowerPoint Presentations with JavaScript in React
2025-02-27 01:06:09 Written by KoohjiPowerPoint presentations often contain sensitive or proprietary information, making it essential to secure them from unauthorized access or modifications. Whether you're sharing a presentation with colleagues, clients, or stakeholders, protecting your slides ensures that your content remains intact and confidential. On the other hand, there may be times when you need to unprotect a presentation to make edits or updates. In this guide, we'll explore how to protect and unprotect PowerPoint presentations programmatically in React using Spire.Presentation for JavaScript.
- Protect a PowerPoint Presentation with a Password
- Make a PowerPoint Presentation Read-Only
- Remove Password Protection from a PowerPoint Presentation
- Remove Read-Only Setting from a PowerPoint Presentation
Install Spire.Presentation for JavaScript
To get started with protecting and unprotecting PowerPoint presentations in a React application, you can either download Spire.Presentation for JavaScript from the official website or install it via npm with the following command:
npm i spire.presentation
After that, copy the "Spire.Presentation.Base.js" and "Spire.Presentation.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Presentation for JavaScript in a React Project.
Protect a PowerPoint Presentation with a Password
Setting a password on a PowerPoint presentation is an effective way to ensure that only authorized users can access its content. By using the Presentation.Encrypt() method of Spire.Presentation for JavaScript, developers can encrypt a PowerPoint presentation with ease. The key steps are as follows.
- Create an object of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Encrypt the presentation with a password using the Presentation.Encrypt() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to protect a PowerPoint file with a password
const ProtectPowerPointPresentation = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Sample.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
// Define the password
let password = "e-iceblue";
// Protect the PowerPoint file with the password
ppt.Encrypt(password);
// Define the output file name
const outputFileName = "Encrypted.pptx";
// Save the resulting PowerPoint file
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });
// Read the generated PowerPoint file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PowerPoint file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Protect a PowerPoint Presentation with a Password</h1>
<button onClick={ProtectPowerPointPresentation} disabled={!wasmModule}>
Protect
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Protect" button to protect the PowerPoint presentation with a password:

Upon opening the output presentation, a dialog box will appear, prompting you to enter a password to gain access to the file:

Make a PowerPoint Presentation Read-Only
Enabling the read-only setting prevents others from making changes to a PowerPoint presentation while still allowing them to view it. Spire.Presentation for JavaScript offers the Presentation.Protect() method to achieve this purpose. The key steps are as follows.
- Create an object of the Presentation class.
- Load a PowerPoint presentation using the Presentation.LoadFromFile() method.
- Make the presentation read-only using the Presentation.Protect() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to make a PowerPoint file ready only
const MakePresentationReadOnly = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Sample.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
// Define the password
let password = "e-iceblue";
// Make the PowerPoint file read-only by protecting it with the password
ppt.Protect(password);
// Define the output file name
const outputFileName = "ReadOnly.pptx";
// Save the resulting PowerPoint file
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });
// Read the generated PowerPoint file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PowerPoint file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Make a PowerPoint Presentation Read-Only</h1>
<button onClick={MakePresentationReadOnly} disabled={!wasmModule}>
Start
</button>
</div>
);
}
export default App;

Remove Password Protection from a PowerPoint Presentation
If password protection is no longer needed, it can be easily removed to allow unrestricted access to the presentation using the Presentation.RemoveEncryption() method. The key steps are as follows.
- Create an object of the Presentation class.
- Load a password-protected PowerPoint presentation with its password using the Presentation.LoadFromFile() method.
- Remove password protection from the presentation using the Presentation.RemoveEncryption() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to remove password encryption from a PowerPoint file
const RemoveEncryptionFromPresentation = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Encrypted.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile({file: inputFileName, password: "your password"});
//Remove the password encryption
ppt.RemoveEncryption();
// Define the output file name
const outputFileName = "Decrypted.pptx";
// Save the resulting PowerPoint file
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });
// Read the generated PowerPoint file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PowerPoint file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Remove Password Protection from a PowerPoint Presentation</h1>
<button onClick={RemoveEncryptionFromPresentation} disabled={!wasmModule}>
Start
</button>
</div>
);
}
export default App;

Remove Read-Only Setting from a PowerPoint Presentation
Disabling the read-only setting allows others to edit the presentation and make necessary changes. By using the Presentation.RemoveProtect() method, developers can remove the read-only setting from a PowerPoint presentation. The key steps are as follows.
- Create an object of the Presentation class.
- Load a PowerPoint presentation that has been made as read-only using the Presentation.LoadFromFile() method.
- Remove the read-only setting from the presentation using the Presentation.RemoveProtect() method.
- Save the resulting presentation using the Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to remove the read-only setting from a PowerPoint file
const RemoveReadOnlyFromPresentation = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "ReadOnly.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
// Remove the read-only setting from the presentation
ppt.RemoveProtect();
// Define the output file name
const outputFileName = "RemoveReadOnly.pptx";
// Save the resulting PowerPoint file
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Pptx2013 });
// Read the generated PowerPoint file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PowerPoint file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Remove Read-Only Setting from a PowerPoint Presentation</h1>
<button onClick={RemoveReadOnlyFromPresentation} disabled={!wasmModule}>
Start
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Presentation for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Transforming PowerPoint presentations into image formats such as JPG or PNG is an effective method for enhancing the way you share visual content. By converting slides into images, you maintain the integrity of the design and layout, making it suitable for a wide range of uses, from online sharing to embedding in documents.
In this article, you will discover how to convert PowerPoint slides to images in React using Spire.Presentation for JavaScript. We will guide you through the process step-by-step, ensuring you can effortlessly create high-quality images from your presentations.
Install Spire.Presentation for JavaScript
To get started with converting PowerPoint to images in a React application, you can either download Spire.Presentation for JavaScript from the official website or install it via npm with the following command:
npm i spire.presentation
After that, copy the "Spire.Presentation.Base.js" and "Spire.Presentation.Base.wasm" files to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Presentation for JavaScript in a React Project.
Convert PowerPoint to PNG or JPG with JavaScript
Using Spire.Presentation for JavaScript, you can access a specific slide with the Presentation.Slides.get_Item() method. Once you have the slide, convert it to image data using ISlide.SaveAsImage(). You can then save the image in PNG or JPG format. To convert each slide into a separate image file, simply iterate through the slides and perform the conversion for each one.
The steps to convert PowerPoint to PNG or JPG using JavaScript are as follows:
- Load required font files into the virtual file system (VFS).
- Instantiate a new document using the wasmModule.Presentation.Create() method
- Load the PowerPoint document using the Presentation.LoadFromFile() method.
- Loop through the slides in the document:
- Get a specific slide using the Presentation.Slides.get_Item() method.
- Convert the slide into image data using the ISlide.SaveAsImage() method.
- Save the image data to a PNG or JPG file using the Save() method of the image data object.
- Create a Blob object from the generated image file.
- Trigger the download of the image file.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert PowerPoint to PNG
const PowerPointToPNG = async () => {
if (wasmModule) {
// Load the font files used the PowerPoint file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input PowerPoint file into the virtual file system
const inputFileName = "ToImage.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a PowerPoint document
const presentation = wasmModule.Presentation.Create();
// Load the PowerPoint file
presentation.LoadFromFile(inputFileName);
// Iterate through the slides
for (let i = 0; i < presentation.Slides.Count; i++) {
// Convert a specific slide into image data
let image = presentation.Slides.get_Item(i).SaveAsImage();
// Specify the output file name
let outputFileName = `ToImage_img_${i}.png`;
// Save each image in virtual storage
image.Save(outputFileName);
// Read the generated image file from VFS
const imageFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the image file
const imageBlob = new Blob([imageFileArray], { type: "image/png" });
// Create a URL for the Blob
const url = URL.createObjectURL(imageBlob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
// Clean up resources
presentation.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PowerPoint to PNG in React</h1>
<button onClick={PowerPointToPNG} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Click "Generate", and a "Save As" window will appear, prompting you to save the output file in your chosen folder.

Below is a screenshot of the generated PNG image files:

Convert PowerPoint to SVG with JavaScript
Spire.Presentation for JavaScript provides the ISlide.SaveToSVG() method, allowing you to convert a slide into SVG byte data. This byte data can then be saved as an SVG file using the Save() method.
The following are the steps to convert PowerPoint to SVG using JavaScript:
- Load required font files into the virtual file system (VFS).
- Instantiate a new document using the wasmModule.Presentation.Create() method
- Load the PowerPoint document using the Presentation.LoadFromFile() method.
- Loop through the slides in the document:
- Get a specific slide using the Presentation.Slides.get_Item() method.
- Convert the slide into SVG byte data using the ISlide.SaveToSVG() method.
- Save the byte data to an SVG file using the Save() method.
- Create a Blob object from the generated image file.
- Trigger the download of the image file.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert PowerPoint to SVG
const PowerPointToSVG = async () => {
if (wasmModule) {
// Load the font files used the PowerPoint file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input PowerPoint file into the virtual file system
const inputFileName = "ToImage.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a PowerPoint document
const presentation = wasmModule.Presentation.Create();
// Load the PowerPoint file
presentation.LoadFromFile(inputFileName);
// Iterate through the slides
for (let i = 0; i < presentation.Slides.Count; i++) {
// Get a specific slide
let slide = presentation.Slides.get_Item(i);
// Convert the slide into SVG bytes
let image = slide.SaveToSVG()
// Specify the output file name
let outputFileName = `ToImage_img_${i}.svg`;
// Save each image in virtual storage
image.Save(outputFileName);
// Read the generated image file from VFS
const imageFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the image file
const imageBlob = new Blob([imageFileArray], { type: "image/svg" });
// Create a URL for the Blob
const url = URL.createObjectURL(imageBlob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
};
// Clean up resources
presentation.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PowerPoint to SVG in React</h1>
<button onClick={PowerPointToSVG} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;

Convert PowerPoint to TIFF with JavaScript
Spire.Presentation for JavaScript includes the Presentation.SaveToFile() method, which allows you to convert an entire PowerPoint document into a multi-frame TIFF image seamlessly.
The following are the steps to convert PowerPoint to TIFF using JavaScript:
- Load required font files into the virtual file system (VFS).
- Instantiate a new document using the wasmModule.Presentation.Create() method
- Load the PowerPoint document using the Presentation.LoadFromFile() method.
- Convert the document to a TIFF image file using the Presenatation.SaveToFile() method.
- Create a Blob object from the generated image file.
- Trigger the download of the image file.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert PowerPoint to TIFF
const PowerPointToTIFF = async () => {
if (wasmModule) {
// Load the font files used the PowerPoint file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the input PowerPoint file into the virtual file system
const inputFileName = "ToImage.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a PowerPoint document
const presentation = wasmModule.Presentation.Create();
// Load the PowerPoint file
presentation.LoadFromFile(inputFileName);
// Specify the output file name
const outputFileName = "ToTIFF.tiff"
// Save the document to TIFF
presentation.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.Tiff });
// Read the generated image file from VFS
const imageFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blog object from the image file
const imageBlob = new Blob([imageFileArray], { type: "image/tiff" });
// Create a URL for the Blob
const url = URL.createObjectURL(imageBlob);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
presentation.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert PowerPoint to TIFF in React</h1>
<button onClick={PowerPointToTIFF} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Presentation for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Converting PowerPoint presentations to PDF ensures that slide content remains intact while making the file easier to share and view across different devices. The PDF format preserves the original layout, text, and images, preventing unintended modifications and ensuring consistent formatting. This conversion is especially useful for professional and academic settings, where maintaining document integrity and accessibility is essential. Additionally, PDFs offer enhanced security features, such as restricted editing and password protection, making them a reliable choice for distributing important presentations. In this article, we will demonstrate how to convert PowerPoint presentations to PDF in React using Spire.Presentation for JavaScript.
- Convert a PowerPoint Presentation to PDF
- Convert a PowerPoint Presentation to PDF with a Custom Page Size
- Convert a PowerPoint Slide to PDF
Install Spire.Presentation for JavaScript
To get started with converting PowerPoint to PDF in a React application, you can either download Spire.Presentation for JavaScript from the official website or install it via npm with the following command:
npm i spire.presentation
Make sure to copy all the dependencies to the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Presentation for JavaScript in a React Project.
Convert a PowerPoint Presentation to PDF
Converting a PowerPoint presentation to PDF allows you to share the entire document while preserving its original layout. Using the Presentation.SaveToFile() method, developers can export the full presentation to a PDF file. Below are the detailed steps to perform this operation.
- Create an object of Presentation class.
- Load a presentation file using Presentation.LoadFromFile() method.
- Save the presentation to a PDF document using Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert a PowerPoint file to PDF
const ConvertPowerPointToPDF = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Sample.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
// Define the output file name
const outputFileName = "PowerPointToPDF.pdf";
// Save the PowerPoint file to PDF format
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.PDF });
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert a PowerPoint Presentation to PDF in React</h1>
<button onClick={ConvertPowerPointToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to convert the PowerPoint presentation to PDF:

The below screenshot shows the input PowerPoint presentation and the converted PDF:

Convert a PowerPoint Presentation to PDF with a Custom Page Size
Developers can customize the page size of the resulting PDF by adjusting the slide size using the Presentation.SlideSize.Type property during conversion. This ensures that the converted PDF meets specific formatting or printing needs. Here are the detailed steps for this operation.
- Create an object of Presentation class.
- Load a presentation file using Presentation.LoadFromFile() method.
- Set the slide size to A4 using Presentation.SlideSize.Type property.
- Save the presentation to a PDF document using Presentation.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert a PowerPoint file to PDF
const ConvertPowerPointToPDF = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Sample.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
//Set A4 page size
ppt.SlideSize.Type = wasmModule.SlideSizeType.A4;
// Define the output file name
const outputFileName = "ToPdfWithSpecificPageSize.pdf";
// Save the PowerPoint file to PDF format
ppt.SaveToFile({ file: outputFileName, fileFormat: wasmModule.FileFormat.PDF });
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert a PowerPoint Presentation to PDF with a Custom Page Size in React</h1>
<button onClick={ConvertPowerPointToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Convert a PowerPoint Slide to PDF
Converting a single PowerPoint slide to PDF allows for easy extraction and sharing of individual slides without exporting the entire presentation. Using the ISlide.SaveToFile() method, developers can convert individual slides to PDF with ease. The detailed steps for this operation are as follows.
- Create an object of the Presentation class.
- Load a presentation file using Presentation.LoadFromFile() method.
- Get a slide using Presentation.Slides.get_Item() method.
- Save the slide as a PDF document using ISlide.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert a PowerPoint file to PDF
const ConvertPowerPointSlideToPDF = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS) to ensure proper rendering
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Load the PowerPoint file into the virtual file system (VFS)
const inputFileName = "Sample.pptx";
await wasmModule.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/`);
// Create a Presentation instance and load the PowerPoint file from the virtual file system
const ppt = wasmModule.Presentation.Create();
ppt.LoadFromFile(inputFileName);
// Get the second slide
let slide = ppt.Slides.get_Item(1);
// Define the output file name
const outputFileName = "SlideToPdf.pdf";
// Save the slide to PDF format
slide.SaveToFile( outputFileName, wasmModule.FileFormat.PDF);
// Read the generated PDF file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PDF file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/pdf"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
ppt.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert a PowerPoint Slide to PDF in React</h1>
<button onClick={ConvertPowerPointSlideToPDF} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.Presentation for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Spire.PDF for JavaScript is a leading PDF API that allows developers to easily create, read, edit, and convert PDFs. Using this JavaScript PDF component, developers can easily implement advanced features to create PDF files from scratch or fully process existing PDF documents within their JavaScript applications.
This versatile JavaScript library offers a wide range of features, including security settings, text/image extraction, PDF merging/splitting, drawing text/image/shape/barcodes, creating and filling in form fields, adding and deleting layers, overlaying PDFs, inserting watermarks (text/image), managing bookmarks, adding tables, adding annotations, and compressing PDF documents, among others.
Spire.Presentation for JavaScript Program Guide Content - React
2025-02-17 01:22:00 Written by KoohjiSpire.Presentation for JavaScript is a powerful presentation processing library designed for developers in JavaScript applications. It is fully compatible with popular JavaScript frameworks like Vue, React, and Angular. This compatibility allows developers to effortlessly integrate Spire.Presentation into their applications, enabling seamless creation, editing, conversion, and distribution of PowerPoint presentations directly within web-based projects.
As a standalone API, Spire.Presentation for JavaScript eliminates the need for Microsoft PowerPoint, making it highly efficient and flexible. Spire.Presentation for JavaScript supports Microsoft PowerPoint 97-2003 and Microsoft PowerPoint 2007, 2010, 2016, and 2019 (PPTX, PPSX).
How to Integrate Spire.Presentation for JavaScript in a React Project
2025-02-21 00:55:01 Written by KoohjiIn the ever-evolving world of web development, React continues to be the preferred framework for creating engaging and responsive user interfaces. For developers looking to enhance their applications with robust presentation capabilities, Spire.Presentation for JavaScript emerges as an invaluable resource.
In this guide, we'll explore the steps to effectively integrate Spire.Presentation for JavaScript into your React application, ensuring you can leverage its robust features for tasks such as generating slides, editing content, and exporting presentations in various formats.
- Benefits of Using Spire.Presentation for JavaScript in React
- Set Up Your Environment
- Integrate Spire.Presentation for JavaScript in Your Project
- Create and Save PowerPoint Files Using JavaScript
Benefits of Using Spire.Presentation for JavaScript in React
React, a powerful JavaScript library for building interactive user interfaces, has become a cornerstone in modern web development. Complementing this is Spire.Presentation for JavaScript, a specialized library designed to enhance PowerPoint presentation management within web applications.
By integrating Spire.Presentation for JavaScript into your React project, you can unlock advanced features for creating and manipulating presentations easily. Here are some of the key benefits:
- Rich Functionality: Spire.Presentation for JavaScript offers a comprehensive range of features for managing PowerPoint files, including creating slides, adding text, images, charts, and shapes. This rich functionality allows developers to build robust presentation applications without needing to rely on external tools.
- Seamless Integration: Designed to work harmoniously with various JavaScript frameworks, including React, Spire.Presentation for JavaScript integrates smoothly into existing projects, facilitating an efficient and enjoyable development experience.
- Cross-Platform Compatibility: Spire.Presentation for JavaScript is designed to work across different platforms and devices. Whether your application is run on desktop, tablet, or mobile devices, you can expect consistent performance and functionality.
- High-Quality Output: Spire.Presentation for JavaScript ensures that the presentations you create are of high quality, maintaining the integrity of fonts, images, and layouts. This quality is crucial for professional presentations and business-related use cases.
Set Up Your Environment
Step 1. Install React and npm
Download and install Node.js from the official website. Make sure to choose the version that matches your operating system.
After the installation is complete, you can verify that Node.js and npm are working correctly by running the following commands in your terminal:

Step 2. Create a New React Project
Create a new React project named my-app using Create React App from terminal:
npx create-react-app my-app

If your React project is compiled successfully, the app will be served at http://localhost:3000, allowing you to view and test your application in a browser.

To visually browse and manage the files in your project, you can open the project using VS Code.

Integrate Spire.Presentation for JavaScript in Your Project
Download Spire.Presentation for JavaScript from our website and unzip it to a location on your disk. Inside the lib folder, you will find the Spire.Presentation.Base.js and Spire.Presentation.Base.wasm files.

Alternatively, you can download Spire.Presentation for JavaScript using npm. In the terminal within VS Code, run the following command:
npm i spire.presentation

Once the installation is complete, the Spire.Presentation.Base.js and Spire.Presentation.Base.wasm files will be saved in the node_modules/spire.presentation path of your project.

Copy these two files into the "public" folder in your React project.

Add font files you plan to use to the "public" folder in your project. (Not always necessary)

Create and Save PowerPoint Files Using JavaScript
Modify the code in the "App.js" file to generate a PowerPoint file using the WebAssembly (WASM) module.

- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and Spire.Presentation from the global window object
const { Module, spirepresentation } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirepresentation);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Presentation.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to create a PowerPoint file
const CreatePowerPoint = async () => {
if (wasmModule) {
// Load the font file into the virtual file system (VFS)
await wasmModule.FetchFileToVFS('ARIALUNI.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Create a PowerPoint document
const presentation = wasmModule.Presentation.Create();
// Set silde size type
presentation.SlideSize.Type = wasmModule.SlideSizeType.Screen16x9;
// Add a new shape
const rec = wasmModule.RectangleF.FromLTRB(presentation.SlideSize.Size.Width / 2 - 250,80,(500 + presentation.SlideSize.Size.Width / 2 - 250),230);
const shape = presentation.Slides.get_Item(0).Shapes.AppendShape({shapeType:wasmModule.ShapeType.Rectangle,rectangle:rec});
// Format the shape
shape.ShapeStyle.LineColor.Color = wasmModule.Color.get_White();
shape.Fill.FillType = wasmModule.FillFormatType.None;
// Add text to the shape
shape.AppendTextFrame("Hello World!");
// Format the text
const textRange = shape.TextFrame.TextRange;
textRange.Fill.FillType = wasmModule.FillFormatType.Solid;
textRange.Fill.SolidColor.Color = wasmModule.Color.get_CadetBlue();
textRange.FontHeight = 66;
textRange.LatinFont = wasmModule.TextFont;
// Define the output file name
const outputFileName = "HelloWorld.pptx";
// Save to file
presentation.SaveToFile({file:outputFileName,fileFormat:wasmModule.FileFormat.Pptx2013});
// Read the generated PowerPoint file
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
// Create a Blob object from the PowerPoint file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.presentationml.presentation"});
// Create a URL for the Blob
const url = URL.createObjectURL(modifiedFile);
// Create an anchor element to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources
presentation.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Create a PowerPoint Document in React</h1>
<button onClick={CreatePowerPoint} disabled={!wasmModule}>
Generate
</button>
</div>
);
}
export default App;
Save the changes by clicking "File" - "Save".

Start the development server by entering the following command in the terminal within VS Code:
npm start

Once the React app is successfully compiled, it will open in your default web browser, typically at http://localhost:3000.

Click "Generate," and a "Save As" window will prompt you to save the output file in the designated folder.

Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Create a Table of Contents in a Word Document Using JavaScript in React
2025-02-20 07:02:53 Written by KoohjiAutomatically generating a table of contents (TOC) in a Word document using JavaScript within a React application streamlines document creation by eliminating manual updates and ensuring dynamic consistency. This approach is particularly valuable in scenarios where content length, structure, or headings frequently change, such as in report-generation tools, academic platforms, or documentation systems. By leveraging Spire.Doc for JavaScript's WebAssembly module and React’s reactive state management, developers can programmatically detect headings, organize hierarchical sections, and insert hyperlinked TOC entries directly into Word files. In this article, we will explore how to use Spire.Doc for JavaScript to insert tables of contents into Word documents with JavaScript in React applications.
- Insert a Default TOC into a Word Document Using JavaScript
- Insert a Custom TOC into a Word Document Using JavaScript
- Remove the Table of Contents from a Word Document
Install Spire.Doc for JavaScript
To get started with inserting tables of contents into Word documents in a React application, you can either download Spire.Doc for JavaScript from our website or install it via npm with the following command:
npm i spire.doc
After that, copy the "Spire.Doc.Base.js" and "Spire.Doc.Base.wasm" files into the public folder of your project. Additionally, include the required font files to ensure accurate and consistent text rendering.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Insert a Default TOC into a Word Document Using JavaScript
Spire.Doc for JavaScript offers a WebAssembly module for processing Word documents in JavaScript environments. You can load a Word document from the virtual file system using the Document.LoadFromFile() method and insert a table of contents (TOC) via the Paragraph.AppendTOC() method, which auto-generates based on the document’s titles. Finally, update the TOC with the Document.UpdateTableOfContents() method.
The detailed steps are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
- Load the Word document from the VFS using the Document.LoadFromFile() method.
- Add a new section to the document using the Document.AddSection() method, and add a paragraph using the Section.AddParagraph() method.
- Insert the section after the cover section using the Document.Sections.Insert() method.
- Insert a TOC into the paragraph using the Paragraph.AppendTOC() method.
- Update the TOC using the Document.UpdateTableOfContents() method.
- Save the document to the VFS using the Document.SaveToFile() method.
- Read the document from the VFS and download it.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to insert a default table of contents into a Word document
const InsertTOCWord = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.docx';
const outputFileName = 'DefaultTOC.docx';
// Fetch the font file and add it to the VFS
await wasmModule.FetchFileToVFS('HarmonyOS_Sans_SC_Regular.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the Document class
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile({ fileName: inputFileName });
// Create a new section
const section = doc.AddSection();
// Create a new paragraph
const paragraph = section.AddParagraph();
// Add a table of contents to the paragraph
paragraph.AppendTOC(1, 2);
// Insert the section after the cover section
doc.Sections.Insert(1, section);
// Update the table of contents
doc.UpdateTableOfContents();
// Save the document to the VFS
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019})
// Read the document from the VFS and create a Blob to trigger the download
const wordArray = await wasmModule.FS.readFile(outputFileName);
const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert Default Table of Contents Using JavaScript in React</h1>
<button onClick={InsertTOCWord} disabled={!wasmModule}>
Insert and Download
</button>
</div>
);
}
export default App;

Insert a Custom TOC into a Word Document Using JavaScript
Spire.Doc for JavaScript also enables users to create a custom table of contents. By creating an instance of the TableOfContent class, you can customize title and page number display using switches. For instance, the switch "{\o "1-3" \n 1-1}" configures the TOC to display titles from level 1 to 3 while omitting page numbers for level 1 titles. After creating the instance, insert it into the document and assign it as the TOC of the document using the Document.TOC property.
The detailed steps are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
- Load the Word document from the VFS using the Document.LoadFromFile() method.
- Add a new section to the document using the Document.AddSection() method, and add a paragraph using the Section.AddParagraph() method.
- Insert the section after the cover section using the Document.Sections.Insert() method.
- Create an instance of the TableOfContent class in the VFS using the wasmModule.TableOfContent.Create() method and specify the switch.
- Insert the TOC into the new paragraph using the Paragraph.Items.Add() method.
- Append the field separator and field end marks to complete the TOC field using the Paragraph.AppendFieldMark() method.
- Set the new TOC as the document’s TOC through the Document.TOC property.
- Update the TOC using the Document.UpdateTableOfContents() method.
- Save the document to the VFS using the Document.SaveToFile() method.
- Read the document from the VFS and download it.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to insert a custom table of contents into a Word document
const InsertTOCWord = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'Sample.docx';
const outputFileName = 'CustomTOC.docx';
// Fetch the font file and add it to the VFS
await wasmModule.FetchFileToVFS('HarmonyOS_Sans_SC_Regular.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/`);
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the Document class
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile({ fileName: inputFileName });
// Add a new section and paragraph
const section = doc.AddSection();
const para = section.AddParagraph();
// Insert the section after the cover section
doc.Sections.Insert(1, section)
// Create an instance of the TableOfContent class and specify the switch
const toc = wasmModule.TableOfContent.Create(doc, '{\\o \”1-3\” \\n 1-1}');
// Add the table of contents to the new paragraph
para.Items.Add(toc);
// Insert a field separator mark to the paragraph
para.AppendFieldMark(wasmModule.FieldMarkType.FieldSeparator);
// Insert a field end mark to the paragraph
para.AppendFieldMark(wasmModule.FieldMarkType.FieldEnd);
// Set the new TOC as the TOC of the document
doc.TOC = toc;
// Update the TOC
doc.UpdateTableOfContents();
// Save the document to the VFS
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019});
// Read the document from the VFS and create a Blob to trigger the download
const wordArray = await wasmModule.FS.readFile(outputFileName);
const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert a Custom Table of Contents Using JavaScript in React</h1>
<button onClick={InsertTOCWord} disabled={!wasmModule}>
Insert and Download
</button>
</div>
);
}
export default App;

Remove the Table of Contents from a Word Document
Since TOC paragraphs have style names that start with "TOC", you can locate them by matching a regular expression on the paragraph style and then remove those paragraphs.
The detailed steps are as follows:
- Load the Spire.Doc.Base.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the wasmModule.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the wasmModule.Document.Create() method.
- Load the Word document from the VFS using the Document.LoadFromFile() method.
- Create an instance of the Regex class with the pattern "TOC\w+".
- Iterate through each section in the document and access its body using the Document.Sections.get_Item().Body property.
- Loop through the paragraphs in each section body and retrieve each paragraph's style via the Paragraph.StyleName property.
- Identify paragraphs whose style matches the regex using the Regex.IsMatch() method and remove them using the Section.Body.Paragraphs.RemoveAt() method.
- Save the document to the VFS using the Document.SaveToFile() method.
- Read the document from the VFS and download it.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to store the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spiredoc from the global window object
const { Module, spiredoc } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spiredoc);
};
} catch (err) {
// Log any errors that occur during module loading
console.error('Failed to load the WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Doc.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to remove the table of contents from a Word document
const InsertTOCWord = async () => {
if (wasmModule) {
// Specify the input and output file names
const inputFileName = 'CustomTOC.docx';
const outputFileName = 'RemoveTOC.docx';
// Fetch the input file and add it to the VFS
await wasmModule.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/`);
// Create an instance of the Document class
const doc = wasmModule.Document.Create();
// Load the Word document
doc.LoadFromFile({ fileName: inputFileName });
// Create a regex pattern to match the style name of TOC
const regex = wasmModule.Regex.Create("TOC\\w+", wasmModule.RegexOptions.None);
// Iterate through each section
for (let i = 0; i < doc.Sections.Count; i++) {
// Iterate through each paragraph in the section body
const sectionBody = doc.Sections.get_Item(i).Body;
for (let j = 0; j < sectionBody.Paragraphs.Count; j++) {
// Check if the style name matches the regex pattern
const paragraph = sectionBody.Paragraphs.get_Item(j);
if (regex.IsMatch(paragraph.StyleName)) {
// Remove the paragraph
sectionBody.Paragraphs.RemoveAt(j)
// Or remove the section
//doc.Sections.RemoveAt(i)
//i--
j--
}
}
}
// Save the document to the VFS
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2019});
// Read the document from the VFS and create a Blob to trigger the download
const wordArray = await wasmModule.FS.readFile(outputFileName);
const blob = new Blob([wordArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${outputFileName}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert a Custom Table of Contents Using JavaScript in React</h1>
<button onClick={InsertTOCWord} disabled={!wasmModule}>
Insert and Download
</button>
</div>
);
}
export default App;
Get a Free License
To fully experience the capabilities of Spire.Doc for JavaScript without any evaluation limitations, you can request a free 30-day trial license.
Convert Text to Numbers or Numbers to Text in Excel with JavaScript in React
2025-02-17 03:12:47 Written by KoohjiProper data formatting is essential for accurate calculations, sorting, and analysis. In Excel, numbers are sometimes mistakenly stored as text, which prevents them from being used in mathematical calculations. On the other hand, certain values like ZIP codes, phone numbers, and product IDs should be stored as text to preserve leading zeros and ensure consistency. Knowing how to convert between text and numeric formats is essential for maintaining data integrity, preventing errors, and improving usability. In this article, you will learn how to convert text to numbers and numbers to text in Excel in React using Spire.XLS for JavaScript.
Install Spire.XLS for JavaScript
To get started with converting text to numbers and numbers to text in Excel in a React application, you can either download Spire.XLS for JavaScript from our website or install it via npm with the following command:
npm i spire.xls
After that, copy the "Spire.Xls.Base.js" and "Spire.Xls.Base.wasm" files to the public folder of your project.
For more details, refer to the documentation: How to Integrate Spire.XLS for JavaScript in a React Project
Convert Text to Numbers in Excel
With Spire.XLS for JavaScript, developers can format the text in individual cells or a range of cells as numbers using the CellRange.ConvertToNumber() method. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load the Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet using the Workbook.Worksheets.get(index) method.
- Get the desired cell or range of cells using the Worksheet.Range.get() method.
- Format the text in the cell or range of cells as numbers using the CellRange.ConvertToNumber() method.
- Save the resulting workbook using the Workbook.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirexls from the global window object
const { Module, spirexls } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirexls);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert text to numbers in an Excel worksheet
const ConvertTextToNumbers = async () => {
if (wasmModule) {
// Load the sample Excel file into the virtual file system (VFS)
let excelFileName = 'TextToNumbers_Input.xlsx';
await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`);
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Load the Excel file from the virtual file system
workbook.LoadFromFile(excelFileName);
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Get the desired cell range
let range = sheet.Range.get("D2:D6");
// Convert the text in the cell range as numbers
range.ConvertToNumber();
// Define the output file name
const outputFileName = "TextToNumbers_output.xlsx";
// Save the workbook to the specified path
workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 });
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Create a URL for the Blob and initiate the download
const url = URL.createObjectURL(modifiedFile);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources used by the workbook
workbook.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Text to Numbers in Excel Using JavaScript in React</h1>
<button onClick={ConvertTextToNumbers} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Convert" button to format text stored in specific cells of an Excel worksheet as numbers:

The screenshot below shows the input Excel worksheet and the output Excel worksheet:

Convert Numbers to Text in Excel
To convert numbers stored in specific cells or a range of cells as text, developers can use the CellRange.NumberFormat property. The detailed steps are as follows.
- Create a Workbook object using the wasmModule.Workbook.Create() method.
- Load the Excel file using the Workbook.LoadFromFile() method.
- Get a specific worksheet using the Workbook.Worksheets.get(index) method.
- Get the desired cell or range of cells using the Worksheet.Range.get() method.
- Format the numbers in the cell or range of cells as text by setting the CellRange.NumberFormat property to "@".
- Save the resulting workbook using the Workbook.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
// State to hold the loaded WASM module
const [wasmModule, setWasmModule] = useState(null);
// useEffect hook to load the WASM module when the component mounts
useEffect(() => {
const loadWasm = async () => {
try {
// Access the Module and spirexls from the global window object
const { Module, spirexls } = window;
// Set the wasmModule state when the runtime is initialized
Module.onRuntimeInitialized = () => {
setWasmModule(spirexls);
};
} catch (err) {
// Log any errors that occur during loading
console.error('Failed to load WASM module:', err);
}
};
// Create a script element to load the WASM JavaScript file
const script = document.createElement('script');
script.src = `${process.env.PUBLIC_URL}/Spire.Xls.Base.js`;
script.onload = loadWasm;
// Append the script to the document body
document.body.appendChild(script);
// Cleanup function to remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []);
// Function to convert numbers to text in an Excel worksheet
const ConvertNumbersToText = async () => {
if (wasmModule) {
// Load the sample Excel file into the virtual file system (VFS)
let excelFileName = 'NumbersToText_Input.xlsx';
await wasmModule.FetchFileToVFS(excelFileName, '', `${process.env.PUBLIC_URL}`);
// Create a new workbook
const workbook = wasmModule.Workbook.Create();
// Load the Excel file from the virtual file system
workbook.LoadFromFile(excelFileName);
// Get the first worksheet
let sheet = workbook.Worksheets.get(0);
// Get the desired cell range
let range = sheet.Range.get("F2:F9");
// Convert the numbers in the cell range as text
range.NumberFormat = "@"
// Define the output file name
const outputFileName = "NumbersToText_output.xlsx";
// Save the workbook to the specified path
workbook.SaveToFile({ fileName: outputFileName, version: wasmModule.ExcelVersion.Version2010 });
// Read the saved file and convert it to a Blob object
const modifiedFileArray = wasmModule.FS.readFile(outputFileName);
const modifiedFile = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
// Create a URL for the Blob and initiate the download
const url = URL.createObjectURL(modifiedFile);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
// Clean up resources used by the workbook
workbook.Dispose();
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Convert Numbers To Text in Excel Using JavaScript in React</h1>
<button onClick={ConvertNumbersToText} disabled={!wasmModule}>
Convert
</button>
</div>
);
}
export default App;

Get a Free License
To fully experience the capabilities of Spire.XLS for JavaScript without any evaluation limitations, you can request a free 30-day trial license.



