Textbox

Textbox (3)

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:

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:

Page 3 of the sample contract EquipmentPurchaseContract.docx: the signature page

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:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the font and the sample document, and take the target paragraph.
  3. Call AppendTextBox to create the text box, and set its fill, border and internal margins.
  4. Write the text through textBox.Body.AddParagraph() and set the character format.
  5. 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:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the sample contract by creating a Document object and loading EquipmentPurchaseContract.docx.
  3. Add a paragraph at the end of the first section and call AppendTextBox(260, 70) to create the text box.
  4. Set the fill color, border color and internal margins, then write the signing date through Body.AddParagraph() and center it.
  5. 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:

The signature page after the text box is inserted at the end

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:

  1. Load ContractWithTextBoxes.docx, which already contains text boxes.
  2. Walk the Document.TextBoxes collection.
  3. For each text box, walk Body.ChildObjects and accumulate the Text of the paragraphs.
  4. Walk the child objects of each paragraph and count the Picture objects.
  5. 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".

The read result: the text and picture count of each of the three text boxes

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:

  1. Load ContractWithTextBoxes.docx, which needs cleaning.
  2. Read TextBoxes.Count before deletion to confirm the number of text boxes.
  3. Call RemoveAt(index) to remove one text box, or call Clear() to remove them all.
  4. 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:

The signature page before and after deleting the text boxes

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:

  1. Load ContractWithTextBoxes.docx, which contains the text boxes.
  2. Take the text box to adjust through get_Item(index); the example takes index 1, the reminder strip.
  3. Set Format.LayoutFlowAlt to TextDirection.RightToLeft.
  4. Reset the width, height and page coordinates for vertical layout, so that the text lands in the margin.
  5. 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:

The signature page before and after changing the text direction

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.

In practical document layout, a textbox is an ideal container for standalone content — it can be positioned freely without being constrained by the page flow, making it perfect for sidebars, pull quotes, product diagrams, and more. Inserting images or tables into a textbox is a common requirement for achieving rich layouts. Spire.Doc for JavaScript processes Word documents directly in the browser via WebAssembly, using a virtual file system (VFS) to manage fonts and file resources — no backend server required.

This article covers two core features:

For installation and project setup, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc is installed and the WebAssembly module is initialized.


Insert Image into Textbox

Filling a textbox with a picture is a common technique for creating product labels, business cards, or promotional materials. Spire.Doc creates a textbox via the AppendTextBox method, then fills its background with a picture using FillEfects.SetPicture. The core process involves three steps: first, load font files and the target image into the WASM virtual file system via FetchFileToVFS; then create a document, add a textbox with position properties, and apply the picture to the textbox through fill effects; finally, save the document, read the generated file from VFS, wrap it as a Blob, and trigger a browser download.

function App() {
  const InsertImageIntoTextBox = async () => {
    // Get the Spire.Doc WASM module
    const docModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load fonts and the image file into VFS
    const imageFileName = 'Spire.Doc.png';
    await window.spire.FetchFileToVFS(imageFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Create a document
    const doc = new docModule.Document();

    // Add a section
    let section = doc.AddSection();

    // Add a paragraph
    let paragraph = section.AddParagraph();

    // Append a 220x220 textbox to the paragraph
    let tb = paragraph.AppendTextBox(220, 220);

    // Set textbox position
    tb.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
    tb.Format.HorizontalPosition = 50;
    tb.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
    tb.Format.VerticalPosition = 50;

    // Set the textbox fill type to Picture
    tb.Format.FillEfects.Type = docModule.BackgroundType.Picture;

    // Fill the textbox with the image
    tb.Format.FillEfects.SetPicture(imageFileName);

    // Define output file name and save
    const outputFileName = "InsertImageIntoTextBox_output.docx";
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Release resources
    doc.Close();
    doc.Dispose();

    // Read the generated file from VFS and trigger download
    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { 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 Image into a Word Textbox</h1>
      <button onClick={InsertImageIntoTextBox}>
        Generate
      </button>
    </div>
  );
}

export default App;

Image filled into the textbox, automatically scaled to fit

Image filled into the textbox, automatically scaled to fit


Insert Table into Textbox

Embedding structured table data in sidebars or reference areas is a common requirement in technical documents and reports. Spire.Doc supports creating tables within a textbox and adding them directly to the textbox body via the textbox.Body.AddTable method. Compared to creating tables in the main document body, tables inside a textbox can be positioned independently without being affected by page layout. The core process involves three steps: first, load font files into the WASM virtual file system via FetchFileToVFS; then create a document and a textbox, add a table via textbox.Body.AddTable with specified row and column counts, fill data row by row, and apply styles; finally, save the document, read the generated file from VFS, wrap it as a Blob, and trigger a browser download.

function App() {
  const InsertTableIntoTextBox = async () => {
    // Get the Spire.Doc WASM module
    const docModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

    // Load font files into VFS
    await window.spire.FetchFileToVFS('msyh.ttc', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);

    // Create a document
    const doc = new docModule.Document();

    // Add a section
    let section = doc.AddSection();

    // Add a paragraph
    let paragraph = section.AddParagraph();

    // Add a 300x150 textbox
    let textbox = paragraph.AppendTextBox(300, 150);

    // Set textbox position
    textbox.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
    textbox.Format.HorizontalPosition = 140;
    textbox.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
    textbox.Format.VerticalPosition = 50;

    // Add a title paragraph in the textbox
    let textboxParagraph = textbox.Body.AddParagraph();
    let textboxRange = textboxParagraph.AppendText("Table 1");
    textboxRange.CharacterFormat.FontName = "Microsoft YaHei";

    // Insert a table into the textbox
    let table = textbox.Body.AddTable({ showBorder: true });

    // Specify the number of rows and columns
    table.ResetCells(4, 4);

    let data = [
      ["Name", "Age", "Gender", "ID"],
      ["John", "28", "Male", "0023"],
      ["Jane", "30", "Male", "0024"],
      ["Wang Wu", "26", "Female", "0025"]
    ];
    // Populate data into the table
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 4; j++) {
        let tableRange = table.Rows.get_Item(i).Cells.get_Item(j).AddParagraph().AppendText(data[i][j]);
        tableRange.CharacterFormat.FontName = "Microsoft YaHei";
      }
    }

    // Apply table style
    table.ApplyStyle({ builtinTableStyle: docModule.DefaultTableStyle.TableColorful2 });

    // Define output file name and save
    const outputFileName = "InsertTableIntoTextBox_output.docx";
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Release resources
    doc.Close();
    doc.Dispose();

    // Read the generated file from VFS and trigger download
    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { 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 Table into a Word Textbox</h1>
      <button onClick={InsertTableIntoTextBox}>
        Generate
      </button>
    </div>
  );
}

export default App;

Table created inside the textbox, contained within the textbox and freely positionable

Table created inside the textbox, contained within the textbox and freely positionable


FAQ

Image in the textbox is truncated or not fully displayed

Cause: The textbox size does not match the image aspect ratio, so the dimensions specified when creating the textbox cannot fully accommodate the image.

Solution: Adjust the textbox size to match the image proportions, or choose an image that fits the textbox dimensions:

let tb = paragraph.AppendTextBox(400, 300);

Table in the textbox has no visible borders

Cause: The showBorder parameter was not set or was set to false when creating the table, resulting in a borderless table.

Solution: Confirm the showBorder parameter is set to true when creating the table:

let table = textbox.Body.AddTable({ showBorder: true });

Textbox position is not as expected after saving

Cause: The HorizontalOrigin or VerticalOrigin values were configured incorrectly, causing the positioning reference point to differ from what was expected.

Solution: Choose the appropriate origin type based on your requirements, and fine-tune the position using HorizontalPosition / VerticalPosition:

tb.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
tb.Format.HorizontalPosition = 50;
tb.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
tb.Format.VerticalPosition = 50;

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.

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:

Copy
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
Copy
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.

React app runs at localhost:3000

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

Add a text box to a Word document in React

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
Copy
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.

page