Textbox (1)
Add or Remove Text Boxes in Word with JavaScript in React
2025-02-28 06:09:58 Written by AdministratorAdding 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.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
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 new wasmModule.Document() 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() {
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 add text box
const AddTextBox = 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 = "Textbox.docx";
const inputFileName = 'input.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(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;
// Save the document to the specified path
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Read the generated file from VFS
const fileArray = window.dotnetRuntime.Module.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 (
<adiv style={{ textAlign: 'center', height: '300px' }}>
<ah1>Add a text box to Word in React<a/h1>
<abutton onClick={AddTextBox} disabled={!wasmModule}>
Generate
<a/button>
<a/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 new wasmModule.Document() 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() {
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 text box
const RemoveTextBox = 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 = "RemoveTextBox.docx";
const inputFileName = 'Textbox.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(inputFileName);
// Remove the text box at index 0
doc.TextBoxes.RemoveAt(0);
// Remove all text boxes
// doc.TextBoxes.Clear();
// Save the document to the specified path
doc.SaveToFile({ fileName: outputFileName, fileFormat: wasmModule.FileFormat.Docx2013 });
// Read the generated file from VFS
const fileArray = window.dotnetRuntime.Module.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.