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.
