Signature blocks, margin notes and figure labels often sit in text boxes. A text box breaks away from the body flow, so it can be positioned freely without disturbing the surrounding layout; when such documents are generated automatically, the program has to be able not only to create boxes and write content into them, but also to read the text back out of an existing document or remove the boxes while cleaning up a template.
This article uses Spire.Doc for JavaScript to perform four operations in the browser. The example document is a three-page equipment purchase contract, EquipmentPurchaseContract.docx:
- Insert a Text Box into a Word Document
- Read the Content of Text Boxes
- Delete Text Boxes from a Word Document
- Set the Text Direction of a Text Box
For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume that Spire.Doc is installed and the WebAssembly module is initialized.
The sample contract contains a cover, the contracting parties, the equipment list, payment terms and a signature page. The signature page is left blank so that seals, reminder notes and margin labels can be placed on it:

The Object Structure of a Text Box
A text box hangs below a paragraph and holds its own body container, Body. It is not part of the paragraph's body flow, so walking the body never reaches it naturally. The document-level Document.TextBoxes collection records every text box in insertion order and is the main entry point for accessing text boxes.
| Member | Purpose |
|---|---|
paragraph.AppendTextBox(width, height) |
Inserts a text box into the paragraph; width and height are in points |
textBox.Body |
The body container inside the text box |
textBox.Format |
Borders, fill, internal margins, position and text direction |
document.TextBoxes |
The collection of every text box in the document |
document.TextBoxes.RemoveAt(index) |
Removes a text box by index |
document.TextBoxes.Clear() |
Removes every text box |
The general workflow for creating and writing out a text box is as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the font and the sample document, and take the target paragraph.
- Call
AppendTextBoxto create the text box, and set its fill, border and internal margins. - Write the text through
textBox.Body.AddParagraph()and set the character format. - Save the result, read it from the VFS and trigger a browser download.
Text box width, height and internal margins are measured in points. On A4 paper with 2.5 cm margins on both sides, the text area is about 454 points wide, and a text box wider than that presses onto the page margins.
Insert a Text Box into a Word Document
To insert a text box into a Word document, first call paragraph.AppendTextBox(width, height) to create a text box in the target paragraph, then write the content through Body.AddParagraph(). By default the text box is laid out with its paragraph, so the position of the paragraph determines where the box appears on the page.
The appearance of a text box is set entirely through Format; the commonly used members are:
| Member | Description |
|---|---|
Format.FillColor |
Fill color, taken from Color.FromArgb(a, r, g, b) |
Format.LineStyle |
Border line style, from the TextBoxLineStyle enumeration |
Format.LineColor / Format.LineWidth |
Border color and line width |
Format.NoLine |
Set to true to hide the border |
Format.InternalMargin |
The distance from the text to the border, with top, bottom, left and right parts |
The specific steps are as follows:
- Get the Spire.Doc WASM module and confirm that it is ready.
- Load the sample contract by creating a
Documentobject and loadingEquipmentPurchaseContract.docx. - Add a paragraph at the end of the first section and call
AppendTextBox(260, 70)to create the text box. - Set the fill color, border color and internal margins, then write the signing date through
Body.AddParagraph()and center it. - Save the result, read it from the VFS and trigger a browser download.
The code for inserting a text box into a Word document is as follows:
function App() {
const insertTextBox = async () => {
// Get the Spire.Doc WASM module
const docModule = window.wasmModule?.spiredoc;
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// Load the sample contract
await window.spire.FetchFileToVFS('EquipmentPurchaseContract.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('EquipmentPurchaseContract.docx');
// Add a paragraph at the end of the first section, then create the text box
const paragraph = doc.Sections.get_Item(0).AddParagraph();
// A text box 260 points wide and 70 points high
const textBox = paragraph.AppendTextBox(260, 70);
textBox.Format.FillColor = docModule.Color.FromArgb(255, 245, 247, 250);
textBox.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
textBox.Format.LineColor = docModule.Color.FromArgb(255, 0, 82, 155);
textBox.Format.LineWidth = 0.75;
// Internal margins between the text and the border
textBox.Format.InternalMargin.Top = 6;
textBox.Format.InternalMargin.Bottom = 6;
textBox.Format.InternalMargin.Left = 8;
textBox.Format.InternalMargin.Right = 8;
// The paragraph inside the text box; alignment and font size go on that inner paragraph
const inner = textBox.Body.AddParagraph();
inner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const range = inner.AppendText('Date of signing: ____ / ____ / ____');
range.CharacterFormat.FontSize = 10.5;
range.CharacterFormat.TextColor = docModule.Color.FromArgb(255, 23, 50, 77);
const outputFileName = 'ContractWithTextBox.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read the generated file from the VFS and trigger the download
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Insert a Text Box</h1>
<button onClick={insertTextBox}>Generate</button>
</div>
);
}
export default App;
After insertion, a bordered signing-date text box appears at the end of the signature page:

Insert a Text Box at a Specific Position on the Page
A text box created by AppendTextBox is laid out with its paragraph by default. To pin it to a particular coordinate on the page, set Format.HorizontalOrigin and Format.VerticalOrigin to Page, then give HorizontalPosition and VerticalPosition; coordinates are measured from the top-left corner of the page, in points.
The code below creates three text boxes on the same paragraph: a seal in the supplier column, a reminder strip in the lower-left area, and a vertical label in the right margin. The three boxes share one anchor paragraph, and their positions do not affect each other:
const anchor = doc.Sections.get_Item(0).AddParagraph();
// Seal: 98 x 98 points, positioned over the supplier column on the signature page
const seal = anchor.AppendTextBox(98, 98);
seal.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
seal.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
seal.Format.HorizontalPosition = 474;
seal.Format.VerticalPosition = 205;
seal.Format.NoLine = true;
const sealInner = seal.Body.AddParagraph();
sealInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const sealImage = sealInner.AppendPicture('Seal.png');
sealImage.Width = 80;
sealImage.Height = 80;
// Reminder strip: 306 x 56 points, positioned in the lower-left area of the page
const tip = anchor.AppendTextBox(306, 56);
tip.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
tip.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
tip.Format.HorizontalPosition = 70;
tip.Format.VerticalPosition = 470;
tip.Format.FillColor = docModule.Color.FromArgb(255, 234, 242, 250);
tip.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
tip.Format.LineColor = docModule.Color.FromArgb(255, 46, 117, 182);
const tipInner = tip.Body.AddParagraph();
tipInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
tipInner.AppendText('Signature note: the supplier has sealed the contract; please verify the contract number and amount before signing.')
.CharacterFormat.FontSize = 9;
// Margin label: 32 x 148 points, vertical, in the right margin
const tab = anchor.AppendTextBox(32, 148);
tab.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
tab.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
tab.Format.HorizontalPosition = 540;
tab.Format.VerticalPosition = 420;
tab.Format.FillColor = docModule.Color.FromArgb(255, 23, 50, 77);
tab.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
tab.Format.LineColor = docModule.Color.FromArgb(255, 23, 50, 77);
tab.Format.LayoutFlowAlt = docModule.TextDirection.LeftToRightRotated;
const tabInner = tab.Body.AddParagraph();
tabInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const tabText = tabInner.AppendText('ORIGINAL');
tabText.CharacterFormat.FontSize = 9;
tabText.CharacterFormat.TextColor = docModule.Color.FromArgb(255, 255, 255, 255);
With the three text boxes inserted, the signature page carries the seal, the reminder strip and the margin label at the same time. The read and delete examples later in this article take the resulting file, ContractWithTextBoxes.docx, as their input; the sample repository already provides that file, so any section can be run on its own.
Read the Content of Text Boxes
To read the content of a text box, first enter the box's Body, then walk its paragraphs and pictures. Document.TextBoxes is ordered by insertion and indexed from 0; pictures inside a text box live among the child objects of its paragraphs, so one more level has to be walked.
| Member | Purpose |
|---|---|
document.TextBoxes.Count |
The total number of text boxes |
document.TextBoxes.get_Item(index) |
Gets a text box by index |
textBox.Body.ChildObjects |
The child objects inside the text box |
DocumentObjectType.Paragraph |
Tests whether a child object is a paragraph |
DocumentObjectType.Picture |
Tests whether a child object is a picture |
The specific steps are as follows:
- Load
ContractWithTextBoxes.docx, which already contains text boxes. - Walk the
Document.TextBoxescollection. - For each text box, walk
Body.ChildObjectsand accumulate theTextof the paragraphs. - Walk the child objects of each paragraph and count the
Pictureobjects. - Write the result to a text file in the VFS and trigger the download.
The code for reading the content of text boxes is as follows:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
const results = [];
for (let i = 0; i < doc.TextBoxes.Count; i++) {
const textBox = doc.TextBoxes.get_Item(i);
let text = '';
let pictureCount = 0;
for (let k = 0; k < textBox.Body.ChildObjects.Count; k++) {
const obj = textBox.Body.ChildObjects.get_Item(k);
if (obj.DocumentObjectType !== docModule.DocumentObjectType.Paragraph) continue;
text += obj.Text;
// Pictures are child objects of the paragraph, so one more level has to be walked
for (let j = 0; j < obj.ChildObjects.Count; j++) {
const child = obj.ChildObjects.get_Item(j);
if (child.DocumentObjectType === docModule.DocumentObjectType.Picture) {
pictureCount++;
}
}
}
results.push({ index: i, text: text.trim(), pictureCount });
}
// Write the result to the VFS and download it as a text file
window.dotnetRuntime.Module.FS.writeFile(
'TextBoxes.txt', JSON.stringify(results, null, 2));
const report = window.dotnetRuntime.Module.FS.readFile('TextBoxes.txt');
const reportBlob = new Blob([report], { type: 'text/plain;charset=utf-8' });
const reportUrl = URL.createObjectURL(reportBlob);
const link = document.createElement('a');
link.href = reportUrl;
link.download = 'TextBoxes.txt';
link.click();
URL.revokeObjectURL(reportUrl);
The sample contract contains three text boxes, and the read result is as follows: index 0 is the seal box, with no text and one picture; index 1 is the reminder box, with 114 characters; index 2 is the margin label, with the 8 characters "ORIGINAL".

Text Boxes in Headers and Footers
In testing, a text box inserted into a header is also recorded in Document.TextBoxes, and remains there after the document is saved and loaded again, so the walk above reads it as well. If the business logic needs to tell whether a text box comes from the body or from a header, walk the HeadersFooters of each section and read the header, footer and body collections separately, then classify by source.
Delete Text Boxes from a Word Document
To delete text boxes from a Word document, remove them by index through Document.TextBoxes or clear the collection outright. Every removal shifts the index of the text boxes after it forward by one, so when removing several in a row, process them from the back, or remove index 0 each time.
| Method | Purpose |
|---|---|
document.TextBoxes.RemoveAt(index) |
Removes the text box at the given index |
document.TextBoxes.Clear() |
Removes every text box |
The specific steps are as follows:
- Load
ContractWithTextBoxes.docx, which needs cleaning. - Read
TextBoxes.Countbefore deletion to confirm the number of text boxes. - Call
RemoveAt(index)to remove one text box, or callClear()to remove them all. - Save the result, read it from the VFS and trigger a browser download.
The code for deleting text boxes from a Word document is as follows:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
console.log('Before deletion:', doc.TextBoxes.Count);
// Remove the first text box
doc.TextBoxes.RemoveAt(0);
// Remove every text box (use one or the other)
// doc.TextBoxes.Clear();
console.log('After deletion:', doc.TextBoxes.Count);
const outputFileName = 'ContractNoTextBoxes.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read from the VFS and download as above
After deletion, the seal, the reminder strip and the margin label are all gone from the signature page, while the body, headers and footers are unaffected:

Delete Text Boxes by Condition
When cleaning up a template, usually only one kind of text box is removed, for example temporary notes whose text contains "Signature note". In that case, read the text of each box first and delete only the matches; walking backwards avoids skipping boxes when the indices shift:
// Walk from the back and remove text boxes whose text contains "Signature note"
for (let i = doc.TextBoxes.Count - 1; i >= 0; i--) {
const textBox = doc.TextBoxes.get_Item(i);
let text = '';
for (let k = 0; k < textBox.Body.ChildObjects.Count; k++) {
const obj = textBox.Body.ChildObjects.get_Item(k);
if (obj.DocumentObjectType === docModule.DocumentObjectType.Paragraph) {
text += obj.Text;
}
}
if (text.includes('Signature note')) {
doc.TextBoxes.RemoveAt(i);
}
}
After the sample runs, only the seal and the margin label remain of the three text boxes; the reminder strip is gone.
Set the Text Direction of a Text Box
To set the text direction of a text box, use Format.LayoutFlowAlt, whose values come from the TextDirection enumeration. The property affects only the layout inside the text box, not the body; text is laid out vertically from top to bottom, which suits margin labels, covers and book titles.
| Value | Tested behavior |
|---|---|
TextDirection.RightToLeft |
Text runs vertically, from top to bottom |
TextDirection.LeftToRightRotated |
Text runs vertically, suited to margin and cover labels |
TextDirection.TopToBottom |
Still displayed horizontally in this version |
The name of TopToBottom makes it easy to assume vertical text, but in tested runs with the JavaScript version the value still saves as horizontal text. When vertical layout is required, prefer RightToLeft or LeftToRightRotated, and check the actual rendering in Word after saving.
The specific steps are as follows:
- Load
ContractWithTextBoxes.docx, which contains the text boxes. - Take the text box to adjust through
get_Item(index); the example takes index 1, the reminder strip. - Set
Format.LayoutFlowAlttoTextDirection.RightToLeft. - Reset the width, height and page coordinates for vertical layout, so that the text lands in the margin.
- Save the result, read it from the VFS and trigger a browser download.
The code for setting the text direction of a text box is as follows:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
// Take the reminder text box at index 1
const textBox = doc.TextBoxes.get_Item(1);
// Vertical layout: text runs from top to bottom
textBox.Format.LayoutFlowAlt = docModule.TextDirection.RightToLeft;
// After the switch the width becomes the column width and the height the column length, so both are reset for the content
textBox.Format.Width = 46;
textBox.Format.Height = 560;
// Move it to the left margin
textBox.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
textBox.Format.HorizontalPosition = 16;
textBox.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
textBox.Format.VerticalPosition = 210;
const outputFileName = 'ContractVerticalTextBox.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// Read from the VFS and download as above
After the adjustment, the horizontal reminder strip becomes a vertical label in the left margin, read from top to bottom:

Why the Width and Height Have to Be Reset After Changing the Direction
In horizontal layout, the width of a text box determines how many characters fit on a line and the height determines how many lines fit. After the switch to vertical layout the two swap: the width becomes the number of characters per column and the height the number of characters a column can hold. The reminder text in the example is about 114 characters; at 46 points wide and 560 points high it forms exactly one column and is fully visible. Keeping the original width and height would truncate the text or spill it out of the box, so both have to be estimated again from the character count and the font size.
FAQ
Why can't a text box be reached when walking the body
Cause: A text box is not a paragraph or a table in the body, but a child object hanging below a paragraph. Walking the body only handles the paragraphs and tables in Body.ChildObjects, so it never reaches text boxes.
Solution: Walk Document.TextBoxes directly; if you start from a paragraph, check the DocumentObjectType of its child objects and then access their Body.
Are text boxes in headers and footers read as well
In testing, yes. A text box inserted into a header is also counted in Document.TextBoxes, and remains so after the document is saved and loaded again, so a document-level walk does not miss it. To distinguish the source, walk the body containers in the HeadersFooters of each section separately and classify by source.
Why is an empty paragraph left in the body after deleting a text box
Cause: RemoveAt and Clear remove the text box object itself, but the anchor paragraph that carried it remains. When the anchor paragraph has no other content, it may show up as a blank line on the page.
Solution: Record the paragraph that carries the text box before deletion, and decide afterwards whether to remove that paragraph as well, according to the layout; when cleaning up a template, paragraphs with no text and no child objects can also be handled in one pass.
I set TopToBottom, but the text is still horizontal
Cause: The actual effect of each TextDirection value in the JavaScript version does not fully match its name. In tested runs, TopToBottom still saved as horizontal text, while RightToLeft and LeftToRightRotated produce vertical layout.
Solution: Switch to RightToLeft or LeftToRightRotated, and check the rendering in Word after saving. Different versions may implement the enumeration differently, so recheck after an upgrade.
Why is a text box positioned by page coordinates in the wrong place
There are three common causes: HorizontalOrigin and VerticalOrigin were not set to Page, so the coordinates are treated as paragraph offsets; the coordinates are not in points; or an alignment property such as ShapeVerticalAlignment was set. In tested runs, setting vertical alignment recenters the text box vertically on the page and the earlier VerticalPosition no longer takes effect. Set the page coordinates first, then handle the alignment of the text inside the box.
Get a Free License
Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.
