Insert Images in Word with JavaScript in React
In MS word, images can quickly and easily convey complex information that may be difficult to explain in words alone. Whether you're creating a report, a presentation, a newsletter, or a simple document, adding images can make your content more engaging, informative, and visually appealing. In this article, you will learn how to add images to a Word document in React using Spire.Doc for JavaScript.
- Insert an Image in a Word Document in JavaScript
- Insert an Image at a Specified Location in Word in JavaScript
Install the JavaScript Library
To get started with inserting images in Word 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.office
The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.
For more details, refer to the documentation: How to Integrate Spire.Doc for JavaScript in a React Project
Insert an Image in a Word Document in JavaScript
The Paragraph.AppendPicture() method offered by Spire.Doc for JavaScript allows to insert an image into a Word document. The following are the main steps to insert an image in Word and set its size, text wrapping style using JavaScript.
- Create a new document using the new wasmModule.Document() method.
- Load a Word document using the Document.LoadFromFile() method.
- Get a specified section in the document using the Document.Sections.get_Item() method.
- Get a specified paragraph in the section using the Section.Paragraphs.get_Item() method.
- Add an image to the specified paragraph using the Paragraph.AppendPicture() method.
- Set width, height and text wrapping style for the image.
- Save the result document using Document.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to insert an image in Word
const InsertWordImage = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const inputFileName = 'input.docx';
const outputFileName = "InsertImage.docx";
const imageFile = "logo.png";
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
await window.spire.FetchFileToVFS(imageFile, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile({ fileName: inputFileName });
// Get the first section
const section = doc.Sections.get_Item(0);
// Get the first paragraph
const paragraph = section.Paragraphs.get_Item(0);
// Add the image to the first paragraph
let picture = paragraph.AppendPicture({ imgFile: imageFile });
// Set image width and height
picture.Width = 100;
picture.Height = 100;
// Set text wrapping style for the image
picture.TextWrappingStyle = wasmModule.TextWrappingStyle.Square;
// Save the result document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });
// Release resources
doc.Dispose();
// Read the generated Word file from VFS
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the Word file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// 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);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert an Image in a Word Document Using JavaScript in React</h1>
<button onClick={InsertWordImage} disabled={!wasmModule}>
Execute
</button>
</div>
);
}
export default App;
Run the code to launch the React app at localhost:3000. Once it's running, click on the "Execute" button to download the result file:

The input file and the result file:

Insert an Image at a Specified Location in Word in JavaScript
You can also place the image at any specified location in the Word document through the DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties. The following are the main steps:
- Create a new document using the new wasmModule.Document() method.
- Add a section to the document using the Document.AddSection() method.
- Add a paragraph to the section using the Section.AddParagraph() method.
- Add text to the paragraph and set paragraph style.
- Add an image to the paragraph using the Paragraph.AppendPicture() method.
- Set the horizontal position and vertical position for the image through the DocPicture.HorizontalPosition and DocPicture.VerticalPosition properties.
- Set width, height and text wrapping style for the image.
- Save the result document using Document.SaveToFile() method.
- JavaScript
import React, { useState, useEffect } from 'react';
function App() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to insert an image at a specified location in Word
const InsertImage = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('Arial.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input file name and the output file name
const outputFileName = "WordImage.docx";
const imageFile = "logo.png";
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(imageFile, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Add a section in the document
let section = doc.AddSection();
// Add a paragraph to the section
let paragraph = section.AddParagraph();
// Add text to the paragraph and set paragraph style
paragraph.AppendText("The sample demonstrates how to insert an image at a specified location in a Word document.");
paragraph.ApplyStyle({ builtinStyle: wasmModule.BuiltinStyle.Heading2 });
//Add an image to the paragraph
let picture = paragraph.AppendPicture({ imgFile: imageFile });
// Set image position
picture.HorizontalPosition = 150.0;
picture.VerticalPosition = 70.0;
// Set image width and height
picture.Width = 100;
picture.Height = 100;
// Set text wrapping style for the image
picture.TextWrappingStyle = wasmModule.TextWrappingStyle.Through;
// Save the result document
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx });
// Release resources
doc.Dispose();
// Read the generated Word file from VFS
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
// Create a Blob object from the Word file
const modifiedFile = new Blob([modifiedFileArray], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" });
// 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);
}
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert an Image at a Specified Location in Word Using JavaScript in React</h1>
<<button onClick={InsertImage} disabled={!wasmModule}>
Execute
</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.
Create a Table of Contents in a Word Document Using JavaScript in React
Automatically 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.office
The downloaded product package integrates Spire.Doc for JavaScript, Spire.XLS for JavaScript, Spire.PDF for JavaScript, and Spire.Presentation for JavaScript. To use the features of Spire.Doc for JavaScript, you need to copy the corresponding files (spire.doc.js, Spire.Doc.Wasm.zip, spire.common.js, Spire.Common.Wasm.zip, and the _framework folder) to the public folder of your project. To ensure proper text rendering, you can add relevant font files with a custom path. In the following example, the font is added to the path: public\static\font.
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.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the window.spire.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the new wasmModule.Document() 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() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to insert a default table of contents into a Word document
const InsertTOCWord = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('CALIBRI.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input and output file names
const inputFileName = 'sample.docx';
const outputFileName = 'DefaultTOC.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// 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 window.dotnetRuntime.Module.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.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the window.spire.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the new wasmModule.Document() 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 new wasmModule.TableOfContent() 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() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to insert a default table of contents into a Word document
const InsertTOCWord = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('CALIBRI.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input and output file names
const inputFileName = 'sample.docx';
const outputFileName = 'CustomTOC.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// 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 = new wasmModule.TableOfContent(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 window.dotnetRuntime.Module.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.js file to initialize the WebAssembly module.
- Fetch the Word file to the virtual file system (VFS) using the window.spire.FetchFileToVFS() method.
- Create an instance of the Document class in the VFS using the new wasmModule.Document() 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() {
const [wasmModule, setWasmModule] = useState(null);
// Load Spire.Doc
useEffect(() => {
(async () => {
try {
const publicUrl = process.env.PUBLIC_URL || '';
const spireModule = await import(/* webpackIgnore: true */ `${publicUrl}/spire.doc.js`);
const rawModule = spireModule.default || spireModule;
window.wasmModule = typeof rawModule === 'function'
? await rawModule({ locateFile: p => p.endsWith('.wasm') ? `${publicUrl}/${p}` : p })
: rawModule;
setWasmModule(window.wasmModule);
} catch (error) {
console.error('Failed to load spire.doc.js WASM module:', error);
}
})();
}, []);
// Function to remove the table of contents from a Word document
const RemoveTOC = async () => {
const wasmModule = window.wasmModule.spiredoc;
if (wasmModule) {
// Load the font files into the virtual file system (VFS)
await window.spire.FetchFileToVFS('CALIBRI.ttf', '/Library/Fonts/', `${process.env.PUBLIC_URL}/static/font/`);
// Specify the input and output file names
const inputFileName = 'sample.docx';
const outputFileName = 'RemoveTOC.docx';
// Fetch the input file and add it to the VFS
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// Create an instance of the Document class
const doc = new wasmModule.Document();
// Load the Word document
doc.LoadFromFile({ fileName: inputFileName });
// Create a regex pattern to match the style name of TOC
const regex = new wasmModule.Regex("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 window.dotnetRuntime.Module.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>Remove TOC Using JavaScript in React</h1>
<button onClick={RemoveTOC} 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.