Bookmarks

Bookmarks (4)

Contract, quotation and acceptance templates often follow the same convention: the body says "the details are shown in the table below", and a bookmark below serves as the insertion point where the data table is filled in at generation time. A bookmark is more stable than "after paragraph N": adding or removing body text does not change the bookmark name, so the insertion position never has to be recalculated.

This article uses Spire.Doc for JavaScript to insert tables in the browser. The document is read through the virtual file system (VFS), the table is written, saved and downloaded directly, and the whole process runs on WebAssembly in the browser, with no Office installation and no backend service.

This article covers four features:

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.


Find a Bookmark by Name and Locate the Insertion Point

A bookmark consists of a start marker and an end marker, and both are objects inside a paragraph. The paragraph that holds the start marker decides the insertion position, and the text between the two markers is the bookmark content. Finding a bookmark by name and locating the insertion point uses the following objects:

Object Access Purpose
Bookmark collection doc.Bookmarks All bookmarks in the document
Find by name doc.Bookmarks.FindByName(name) Returns the bookmark object
Start marker bookmark.BookmarkStart Locates the insertion point
Owner paragraph bookmark.BookmarkStart.OwnerParagraph The paragraph's position in the body

The sample in this article uses the quotation template Quotation.docx. The template contains a title block, a customer information table, a service scope table, and two bookmark placeholders for the cost breakdown and the payment schedule, named ItemTable and PaymentTable:

Page 2 of the quotation template: a bookmark placeholder sits where the cost breakdown and the payment schedule belong

The specific steps are as follows:

  1. Get the Spire.Doc WASM module and confirm that it is ready.
  2. Load the quotation template Quotation.docx into the VFS.
  3. Create a Document object and load the template.
  4. Find the bookmark by name with the Document.Bookmarks.FindByName() method, and check whether the return value is empty.
  5. Read BookmarkStart.OwnerParagraph.Text to confirm the text of the paragraph that holds the bookmark.

The code for finding a bookmark by name is as follows:

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

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

    // Load the quotation template
    await window.spire.FetchFileToVFS('Quotation.docx', '', `${process.env.PUBLIC_URL}/data/`);

    const doc = new docModule.Document();
    doc.LoadFromFile('Quotation.docx');

    // Find the bookmark by name; returns null when nothing matches
    const bookmark = doc.Bookmarks.FindByName('ItemTable');

    if (!bookmark) {
      alert('Bookmark ItemTable was not found in the template');
      doc.Dispose();
      return;
    }

    // The paragraph that holds the bookmark start marker
    const anchorParagraph = bookmark.BookmarkStart.OwnerParagraph;
    console.log('Paragraph holding the bookmark:', anchorParagraph.Text);

    doc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Find a Bookmark</h1>
      <button onClick={findBookmark}>Find</button>
    </div>
  );
}

export default App;

After the run the console prints Paragraph holding the bookmark: (Insert the cost breakdown table here), which confirms that the insertion point landed on the cost breakdown placeholder paragraph.

Bookmark Names Are Case-Sensitive

FindByName() matches the name exactly, so a different case finds nothing. Bookmarks in a template are best kept to English letters and underscores, which avoids the matching problems that spaces and punctuation bring. When several bookmarks share a name, the first match in the collection is returned.

How to Locate a Bookmark That Spans Several Paragraphs

When a bookmark crosses paragraphs, the start marker and the end marker are not in the same paragraph, and OwnerParagraph points only to the starting paragraph. To replace the content of the whole bookmark range, handle the paragraph that holds the end marker as well; working on the starting paragraph alone is not enough.

How to Loop Over All Bookmarks in a Document

Bookmarks is a collection object; use Count and get_Item(index) to access it by index:

// Print every bookmark name and its paragraph in turn
for (let i = 0; i < doc.Bookmarks.Count; i++) {
  const bookmark = doc.Bookmarks.get_Item(i);
  console.log(bookmark.Name, bookmark.BookmarkStart.OwnerParagraph.Text);
}

When a template is filled in a batch, this loop can confirm that all the bookmarks are present before the tables are inserted one by one.


Insert a Table at the Bookmark Position

A table is a body-level object and cannot be put inside a paragraph directly. Inserting a table at a bookmark position works like this: create a new table, set its rows and columns, fill in the data, and then insert the table after the bookmark paragraph by using that paragraph's index in the body.

The specific steps are as follows:

  1. Load the template Quotation.docx and find the bookmark ItemTable by name.
  2. Read BookmarkStart.OwnerParagraph to get the paragraph that holds the bookmark.
  3. Create a bordered table with new Table(doc, true) and set its rows and columns with ResetCells(5, 3).
  4. Fill the header and the data rows through Rows, Cells, AddParagraph() and AppendText().
  5. Take the paragraph index with ChildObjects.IndexOf() and insert the table with ChildObjects.Insert(index + 1, table).
  6. Save the result as QuotationWithFeeTable.docx, read the file from the VFS and trigger a browser download.

The code for inserting a table at a bookmark position is as follows:

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

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

    // Load the quotation template
    await window.spire.FetchFileToVFS('Quotation.docx', '', `${process.env.PUBLIC_URL}/data/`);

    const doc = new docModule.Document();
    doc.LoadFromFile('Quotation.docx');

    const bookmark = doc.Bookmarks.FindByName('ItemTable');
    if (!bookmark) {
      alert('Bookmark ItemTable was not found in the template');
      doc.Dispose();
      return;
    }

    // The paragraph that holds the bookmark start marker
    const anchorParagraph = bookmark.BookmarkStart.OwnerParagraph;
    const body = doc.Sections.get_Item(0).Body;

    // Create a bordered table with 5 rows and 3 columns
    const table = new docModule.Table(doc, true);
    table.ResetCells(5, 3);

    const rowsData = [
      ['Service Item', 'Qty', 'Amount (CNY)'],
      ['System deployment and API integration', '1', '120,000'],
      ['AGV scheduling and integration testing', '1', '96,000'],
      ['Bin mapping and workflow configuration', '1', '74,400'],
      ['Go-live support and operator training', '1', '76,800'],
    ];

    for (let r = 0; r < rowsData.length; r++) {
      for (let c = 0; c < rowsData[r].length; c++) {
        table.Rows.get_Item(r).Cells.get_Item(c)
          .AddParagraph().AppendText(rowsData[r][c]);
      }
    }

    // Index of the paragraph in the body; insert the table after it
    const index = body.ChildObjects.IndexOf(anchorParagraph);
    body.ChildObjects.Insert(index + 1, table);

    const outputFileName = 'QuotationWithFeeTable.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 Table at a Bookmark</h1>
      <button onClick={insertTableAtBookmark}>Insert Table</button>
    </div>
  );
}

export default App;

The cost breakdown table now sits after the paragraph that holds the ItemTable bookmark:

The cost breakdown table inserted after the paragraph that holds the ItemTable bookmark; the placeholder text is still there

Why the Table Landed Before the Paragraph

ChildObjects.Insert(index, table) places the table before the object at that index, and after the insertion the table itself takes that index. To put it after the paragraph, the index has to be one higher. When empty paragraphs follow the bookmark paragraph, the table lands before them and still looks attached to the bookmark; for an exact position, remove the empty paragraphs first.

How the Borders of a New Table Are Controlled

The second argument of new Table(doc, true) says whether the table shows borders. With true the table gets a full set of grid lines; with false no border is drawn, which suits layouts decorated by cell shading or outer rules. A new table uses the document's normal table style, and the column widths are split evenly.

Why the Placeholder Text Is Still There After the Table Is Inserted

Inserting a table only changes the order of objects in the body; it does not rewrite the text of the bookmark paragraph. The template's "(Insert the cost breakdown table here)" still sits above the table and has to be cleared separately, as shown in the next section.


Insert Tables at Several Bookmarks in a Batch

A template usually has more than one insertion point. To insert tables at several bookmarks in a batch, wrap "find the bookmark, build the table, fill in the data, insert by index" into a function and call it in a loop over a list of bookmarks. Each bookmark computes its own paragraph index, so a table inserted earlier does not affect the positioning of a later one.

The specific steps are as follows:

  1. Load the template Quotation.docx and prepare the data arrays for the two bookmarks.
  2. Wrap the insertion logic in insertTableAtBookmark(): find the bookmark, build the table, fill it in, insert by index.
  3. Call the function to insert a table at ItemTable and at PaymentTable.
  4. Save the result as QuotationWithTables.docx.
  5. Read the result from the VFS and download it.

The code for inserting tables in a batch is as follows (the module check, font loading and download code shared with the previous section are omitted):

// Insert a table by bookmark name: place the table after the bookmark paragraph
const insertTableAtBookmark = (doc, docModule, bookmarkName, rowsData) => {
  const bookmark = doc.Bookmarks.FindByName(bookmarkName);
  if (!bookmark) return null;

  const table = new docModule.Table(doc, true);
  table.ResetCells(rowsData.length, rowsData[0].length);

  for (let r = 0; r < rowsData.length; r++) {
    for (let c = 0; c < rowsData[r].length; c++) {
      table.Rows.get_Item(r).Cells.get_Item(c)
        .AddParagraph().AppendText(rowsData[r][c]);
    }
  }

  const body = doc.Sections.get_Item(0).Body;
  const index = body.ChildObjects.IndexOf(bookmark.BookmarkStart.OwnerParagraph);
  body.ChildObjects.Insert(index + 1, table);

  return table;
};

const feeRows = [
  ['Service Item', 'Qty', 'Amount (CNY)'],
  ['System deployment and API integration', '1', '120,000'],
  ['AGV scheduling and integration testing', '1', '96,000'],
  ['Bin mapping and workflow configuration', '1', '74,400'],
  ['Go-live support and operator training', '1', '76,800'],
];

const paymentRows = [
  ['Payment Milestone', 'Ratio', 'Amount (CNY)', 'Planned Date'],
  ['Contract signing', '30%', '110,160', '2026-11-15'],
  ['System deployment complete', '30%', '110,160', '2026-12-10'],
  ['Integration acceptance passed', '30%', '110,160', '2027-01-09'],
  ['Warranty expiry', '10%', '36,720', '2027-12-31'],
];

const feeTable = insertTableAtBookmark(doc, docModule, 'ItemTable', feeRows);
const paymentTable = insertTableAtBookmark(doc, docModule, 'PaymentTable', paymentRows);

The quotation after tables are inserted at both bookmark positions:

The quotation after tables are inserted at both bookmark positions (page 2)

How to Skip a Bookmark That Does Not Exist

The function returns null as soon as FindByName() finds nothing, so the caller can check the result before going on. When a template is revised, a bookmark is renamed or a name is misspelled, this step keeps the table from landing in an unexpected place:

const feeTable = insertTableAtBookmark(doc, docModule, 'ItemTable', feeRows);
if (!feeTable) {
  console.warn('Bookmark ItemTable was not found in the template; the cost breakdown table was skipped');
}

Do the Indices Have to Be Recomputed When Several Tables Are Inserted in a Row

They do. ChildObjects.IndexOf() reads the object's position in the current body, and every insertion shifts the index of the objects behind it. The function recomputes the index on each call, so inserting bookmark by bookmark needs no manual offset bookkeeping.


Clear the Placeholder Text and Style the Tables

The bookmarks in a template usually hold placeholder text such as "(Insert the details table here)". It has to be cleared after the table is inserted, or a prompt line stays above the table. Clearing the placeholder and styling the table works like this: clear the text of the placeholder paragraphs, shade the header row and set its text to bold white, allocate the column widths by content, and repeat the header row across pages.

The specific steps are as follows:

  1. Loop over the bookmark collection first and collect the paragraphs that contain "Insert the".
  2. Clear the placeholder text with paragraph.Text = '' and set the space after the paragraph.
  3. Loop over the two tables and set IsHeader of the header row to true.
  4. Shade the header cells, set their text to bold white, and set the column widths with SetColumnWidth().
  5. Save the result as QuotationFinal.docx and download it.

The code for clearing the placeholder text and styling the tables is as follows (the loading, insertion and download code shared with the previous sections is omitted):

// Collect the placeholder paragraphs first: rewriting a paragraph's text removes its bookmarks too
const placeholders = [];
for (let i = 0; i < doc.Bookmarks.Count; i++) {
  const paragraph = doc.Bookmarks.get_Item(i).BookmarkStart.OwnerParagraph;
  if (paragraph.Text.includes('Insert the')) {
    placeholders.push(paragraph);
  }
}

for (const paragraph of placeholders) {
  paragraph.Text = '';
  paragraph.Format.AfterSpacing = 6;
}

// Header row: dark shading, bold white text, repeated across pages
for (const table of [feeTable, paymentTable]) {
  table.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
  table.Rows.get_Item(0).IsHeader = true;

  const header = table.Rows.get_Item(0);
  for (let c = 0; c < header.Cells.Count; c++) {
    const cell = header.Cells.get_Item(c);
    cell.CellFormat.BackColor = docModule.Color.FromArgb(31, 78, 121);
    cell.CellFormat.VerticalAlignment = docModule.VerticalAlignment.Middle;

    // Write the text back before bold and the text colour can be applied
    const paragraph = cell.Paragraphs.get_Item(0);
    const text = paragraph.Text;
    paragraph.Text = '';
    const run = paragraph.AppendText(text);
    run.CharacterFormat.Bold = true;
    run.CharacterFormat.TextColor = docModule.Color.FromArgb(255, 255, 255);
  }
}

// Column widths: allocated in points, the third argument is CellWidthType.Point
const feeWidths = [250, 60, 149];
for (let c = 0; c < feeWidths.length; c++) {
  feeTable.SetColumnWidth(c, feeWidths[c], docModule.CellWidthType.Point);
}

const payWidths = [155, 65, 120, 119];
for (let c = 0; c < payWidths.length; c++) {
  paymentTable.SetColumnWidth(c, payWidths[c], docModule.CellWidthType.Point);
}

The quotation after the placeholder text is cleared and the tables are styled:

The quotation after the placeholder text is cleared and the tables are styled (page 2)

Why the Bookmarks Disappear After the Placeholder Text Is Cleared

paragraph.Text assigns the whole text of the paragraph, and writing new content rebuilds the paragraph contents, so the bookmark markers inside the paragraph disappear with it. In the run, Bookmarks.Count drops from 2 to 0 after the placeholders are cleared. If the same bookmark is needed for a later location, clear the placeholders after the last fill, or add the bookmarks again after the rewrite.

How to Repeat the Header Row Across Pages

When the table has many data rows and breaks across pages, the header row appears only on the first page by default. With IsHeader of the first row set to true, the row repeats at the top of every page:

// The first row acts as the header and repeats across pages
table.Rows.get_Item(0).IsHeader = true;

Why the Column Widths Did Not Take Effect

SetColumnWidth() takes three arguments: the column index, the width value and the width unit. The unit comes from CellWidthType, whose values are Auto, Percentage and Point, with Point meaning points. A call with only two arguments throws, so the unit has to be supplied in the three-argument form.

Can a Table Reuse the Style of an Existing Table in the Template

new Table(doc, true) only decides whether the table shows borders; it does not inherit the style of other tables in the template. To match the template, set the header shading, text colour, alignment and column widths item by item as above; wrap the settings in a function and call it once for each new table.


FAQ

Should the Placeholder Text Be Deleted First, or the Table Inserted First

Both orders produce a table, but deleting the text first changes the state of the bookmark. Clearing the placeholder with paragraph.Text removes the bookmark in the paragraph as well, and a later FindByName() then finds nothing. The safer order is to insert the table first and clear all the placeholder text at the end.

The Table Did Not Appear at the Bookmark Position — What Could Be Wrong

There are three common causes: the insertion index was not raised by one, so the table landed before the paragraph; the bookmark sits in a header, a footer or a text box and is not in the body's Body; the bookmark name differs from the string in the code, case included. Printing the names in Bookmarks and their paragraph text first confirms whether the location is right.

Can Several Tables Be Inserted at One Bookmark

They can; insert repeatedly at the same bookmark. Mind the order: inserting after the bookmark paragraph every time puts a later table before the earlier one. To keep the call order, insert after the previous table instead:

// The first table goes after the bookmark paragraph
const first = insertTableAtBookmark(doc, docModule, 'ItemTable', feeRows);

// The second table goes after the first, keeping the call order
const secondTable = new docModule.Table(doc, true);
secondTable.ResetCells(2, 3);
// …fill in the content
const docBody = doc.Sections.get_Item(0).Body;
docBody.ChildObjects.Insert(docBody.ChildObjects.IndexOf(first) + 1, secondTable);

The Header Row Does Not Repeat When the Table Breaks Across Pages

Set IsHeader of the table's first row to true, and the row appears at the top of every page. If the first row was originally an ordinary data row, it then repeats at the top of each page, so confirm that the header and the data really sit in different rows.

Do These Operations Upload the Document to a Server

No upload is needed for the usage in this article. Spire.Doc for JavaScript runs in the browser on WebAssembly and reads and writes the document locally through the virtual file system (VFS); finding bookmarks, inserting tables and saving the result all happen locally, and the library does not send the file to a server. Whether the file leaves the device at all depends on other code added to the page.


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.

A bookmark is a named anchor that marks a specific position or a range of content in a Word document. Writing content into a bookmark lets business data land at the designated place in a template automatically, without the caller having to know how the document is actually laid out. Spire.Doc for JavaScript performs this entirely in the browser via WebAssembly, using a virtual file system (VFS) to manage fonts, documents and image 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 Document Content at a Bookmark

Inserting document content into a bookmark runs in three stages: first, instantiate two Document objects and load a file into each, one for the document to be filled and one that provides the content; then locate the bookmark by name with BookmarksNavigator.MoveToBookmark, take the bookmark's start marker through CurrentBookmark.BookmarkStart, work out the index of the paragraph holding that bookmark within the section through its OwnerParagraph and the section's IndexOf, and insert every paragraph of the source document after that index (each one Clone()d first); last, save the document, read the generated file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const InsertDocAtBookmark = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    // Load the target document to be filled into VFS
    let inputFileName_1 = "InsertDocAtBookmark1.docx";
    await window.spire.FetchFileToVFS(inputFileName_1, "", `${process.env.PUBLIC_URL}/static/data/`);

    // Load the source document that provides the content into VFS
    let inputFileName_2 = "InsertDocAtBookmark2.docx";
    await window.spire.FetchFileToVFS(inputFileName_2, "", `${process.env.PUBLIC_URL}/static/data/`);

    // Load the target document
    let document1 = new docModule.Document();
    document1.LoadFromFile(inputFileName_1);

    // Load the source document
    let document2 = new docModule.Document();
    document2.LoadFromFile(inputFileName_2);

    // Get the first section of the target document
    let section1 = document1.Sections.get_Item();

    // Create a bookmark navigator to locate the bookmark
    let bn = new docModule.BookmarksNavigator(document1);

    // Find the bookmark by name
    bn.MoveToBookmark("Test", true, true);

    // Get the bookmark's start marker
    let start = bn.CurrentBookmark.BookmarkStart;

    // Get the paragraph that holds the start marker
    let para = start.OwnerParagraph;

    // Get the index of that paragraph in the section
    let index = section1.Body.ChildObjects.IndexOf(para);

    // Insert the paragraphs of the source document one by one after the paragraph holding the bookmark
    for (let i = 0; i < document2.Sections.Count; i++) {
      let section2 = document2.Sections.get_Item(i);
      for (let j = section2.Paragraphs.Count-1; j >=0; j--) {
        let paragraph = section2.Paragraphs.get_Item(j);
        section1.Body.ChildObjects.Insert(index + 1, paragraph.Clone());
      }
    }

    // Define the output file name
    const outputFileName = "InsertDocAtBookmark-result.docx";

    // Save the document
    document1.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    document1.Dispose();
    document2.Dispose();

    // Read the saved file and convert it to a Blob
    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 a document at a Word bookmark</h1>
      <button onClick={InsertDocAtBookmark}>Generate</button>
    </div>
  );
}
export default App;

Word output after the paragraphs of the source document have been inserted at the bookmark

Word output after the paragraphs of the source document have been inserted at the bookmark


Insert an Image at a Bookmark

A bookmark marks a position in the document, so it can carry non-text content just as well — inserting a seal image at a signature bookmark in a contract template, for example. The core process runs in three stages: first, instantiate a Document and load the file; then locate the bookmark with a BookmarksNavigator, create a temporary section with AddSection, add a paragraph inside that temporary section and append the image to it with AppendPicture, insert the whole paragraph at the bookmark with InsertParagraph, and finally remove the temporary section; last, save the document, read the generated file from VFS, wrap it as a Blob and trigger a browser download.

function App() {
  const InsertImageAtBookmark = async () => {
    const docModule = window.wasmModule?.spiredoc;
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    // Load the target document into VFS
    let inputFileName = "InsertImageAtBookmark.docx";
    await window.spire.FetchFileToVFS(inputFileName, "", `${process.env.PUBLIC_URL}/static/data/`);

    // Load the image to be inserted into VFS
    let imageFileName = "Word.png";
    await window.spire.FetchFileToVFS(imageFileName, "", `${process.env.PUBLIC_URL}/static/data/`);

    // Load the document
    let doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Create a bookmark navigator to locate the bookmark
    let bn = new docModule.BookmarksNavigator(doc);

    // Find the bookmark by name
    bn.MoveToBookmark("Test", true, true);

    // Add a temporary section to hold the image paragraph
    let section0 = doc.AddSection();

    // Add a paragraph in the temporary section
    let paragraph = section0.AddParagraph();

    // Append the image to the paragraph
    paragraph.AppendPicture({ imgFile: imageFileName });

    // Insert that paragraph at the bookmark
    bn.InsertParagraph(paragraph);

    // Remove the temporary section
    doc.Sections.Remove(section0);

    // Define the output file name
    const outputFileName = "InsertImageAtBookmark-result.docx";

    // Save the document
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
    doc.Dispose();

    // Read the saved file and convert it to a Blob
    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 an image at a Word bookmark</h1>
      <button onClick={InsertImageAtBookmark}>Generate</button>
    </div>
  );
}
export default App;

Word output after the image has been inserted at the bookmark

Word output after the image has been inserted at the bookmark


FAQ

The bookmark cannot be found and MoveToBookmark fails to locate it

Cause: MoveToBookmark locates a bookmark by its name. The name is case-sensitive and has to match the bookmark name in the document exactly. If the spelling does not match, or the target document has no bookmark with that name at all, the lookup fails.

Solution: Before locating, walk the Bookmarks collection to confirm the bookmark names the document actually carries, then pass the exact name:

// Walk all the bookmarks in the document to check whether the name matches
for (let i = 0; i < doc.Bookmarks.Count; i++) {
  console.log(doc.Bookmarks.get_Item(i).Name);
}

// Once the bookmark is confirmed to exist, locate it by its exact name
let bn = new wasmModule.BookmarksNavigator(doc);
bn.MoveToBookmark("Test", true, true);

The inserted image is larger than the page

Cause: AppendPicture inserts the image at its original pixel size and does not fit it to the page width. If the image resolution is far above the available page width, it overflows the page or stretches the original layout once inserted.

Solution: AppendPicture returns the picture object, so it can be scaled proportionally to a maximum width before it is inserted at the bookmark (Width and Height are measured in points):

// Append the image and keep the returned picture object
let paragraph = section0.AddParagraph();
let picture = paragraph.AppendPicture({ imgFile: imageFileName });

// Scale proportionally to the maximum width
let maxWidth = 400;
if (picture.Width > maxWidth) {
  picture.Height = picture.Height * (maxWidth / picture.Width);
  picture.Width = maxWidth;
}

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.

Bookmarks are invisible positioning markers in Word documents that act as coordinates, precisely marking a location or a range of text. But the true value of bookmarks goes beyond positioning—by programmatically retrieving content within a bookmark range, replacing placeholder text, removing unwanted content, or inserting text, paragraphs, tables, and images at bookmark positions, developers can implement advanced document processing workflows such as automatic contract template filling, dynamic report data injection, and batch form content cleanup. The combination of "read, write, delete, and insert" operations around bookmark content forms the core of Word automation.

Spire.Doc for JavaScript runs entirely in the browser via WebAssembly, handling bookmark content retrieval, replacement, deletion, and element insertion directly — all managed through a virtual file system (VFS) with no backend server required.

This article covers four 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.


Get Bookmark Content

Getting bookmark content is the prerequisite for any bookmark operation. After locating a bookmark with BookmarksNavigator, the GetBookmarkContent method returns the content within the bookmark range as a TextBodyPart object, which developers can iterate through its BodyItems collection to retrieve elements.

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

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

    // Load the Word file into VFS
    const inputFileName = 'ContractTemplate_en.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Create a BookmarksNavigator and move to the bookmark
    let navigator = new docModule.BookmarksNavigator(doc);
    navigator.MoveToBookmark("myBookmark");
    let textBodyPart = navigator.GetBookmarkContent();

    // Iterate through elements in the bookmark content and extract text
    let text = "";
    for (let i = 0; i < textBodyPart.BodyItems.Count; i++) {
      let item = textBodyPart.BodyItems.get_Item(i);
      if (item instanceof docModule.Paragraph) {
        for (let j = 0; j < item.ChildObjects.Count; j++) {
          let childObject = item.ChildObjects.get_Item(j);
          if (childObject instanceof docModule.TextRange) {
            text += childObject.Text;
          }
        }
      }
    }

    // Save as a .txt file
    const outputFileName = "GetBookmarkContent.txt";

    // Write the text file to VFS and trigger download
    window.dotnetRuntime.Module.FS.writeFile(outputFileName, text);

    const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([fileArray], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Get Bookmark Content from Word Document</h1>
      <button onClick={bookmarkContent}>
        Generate
      </button>
    </div>
  );
}

export default App;

Executing the code above extracts the text content from the bookmark "myBookmark" and saves it as a separate .txt file:

Extracted bookmark text content


Replace Bookmark Content

Replacing bookmark content is the most common operation in document template filling. After locating a bookmark with BookmarksNavigator, the ReplaceBookmarkContent method supports replacement with both plain text and complex elements like tables, making it ideal for placeholder replacement in contract generation, report filling, and similar scenarios.

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

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

    // Load fonts and Word file into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'BookmarkSample.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Create a BookmarksNavigator and move to the bookmark
    let navigator = new docModule.BookmarksNavigator(doc);
    navigator.MoveToBookmark("Bookmark1");

    // Replace the content of "书签1" — with text
    navigator.ReplaceBookmarkContent({ text: "This is the text that will replace the bookmark.", saveFormatting: true });

    // Continue to replace "书签2" — with a table
    navigator.MoveToBookmark("Bookmark2");

    // Create a table
    let table = new docModule.Table(doc, true);
    table.ResetCells(4, 5);

    // Create data and fill it into the table
    let dt = [
      ["City", "Province", "Population", "Area (km²)", "Abbrev."],
      ["Beijing", "Beijing", "21.89M", "16410", "BJ"],
      ["Shanghai", "Shanghai", "24.75M", "6340", "SH"],
      ["Guangzhou", "Guangdong", "18.67M", "7434", "GZ"]];
    for (let i = 0; i < 4; i++) {
      for (let j = 0; j < 5; j++) {
        table.Rows.get_Item(i).Cells.get_Item(j).AddParagraph().AppendText(dt[i][j]);
      }
    }

    // Create a TextBodyPart instance and add the table to it
    let part = new docModule.TextBodyPart({ doc: doc });
    part.BodyItems.Add(table);

    // Replace the current bookmark content with the TextBodyPart
    navigator.ReplaceBookmarkContent({ bodyPart: part });

    // Save as a new .docx file
    const outputFileName = "ReplaceBookmark.docx";
    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the generated file from VFS and trigger 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);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Replace Bookmark Content in Word</h1>
      <button onClick={replaceBookmarkContent}>
        Generate
      </button>
    </div>
  );
}

export default App;

This method supports replacing bookmark content with plain text or complex elements like tables. The bookmark marker itself is preserved after replacement, making it easy to locate again later. The figure below shows the result:

Bookmark content replaced with text and table


Delete Bookmark Content

Deleting bookmark content and removing a bookmark marker are two different operations. After locating a bookmark with BookmarksNavigator, calling DeleteBookmarkContent removes the text content within the bookmark range while preserving the bookmark marker itself for later refilling. If you only need to clear the content while keeping the positioning marker, this method is the preferred choice.

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

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

    // Load the Word file into VFS
    const inputFileName = 'ContractTemplate_en.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Create a BookmarksNavigator and move to the bookmark
    let navigator = new docModule.BookmarksNavigator(doc);
    navigator.MoveToBookmark("myBookmark");

    // Delete bookmark content, keep the bookmark marker
    navigator.DeleteBookmarkContent(true);

    // Save as a new .docx file
    const outputFileName = "RemoveBookmark.docx";

    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the generated file from VFS and trigger 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);

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

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Bookmark Content in Word</h1>
      <button onClick={deleteBookmarkContent}>
        Generate
      </button>
    </div>
  );
}

export default App;

DeleteBookmarkContent removes only the text content within the bookmark range — the bookmark marker itself remains. Bookmarks.Remove, on the other hand, removes the bookmark marker, leaving the text within the range unaffected.

After execution, the text within the bookmark "myBookmark" is removed, but the bookmark marker stays in the document:

Bookmark content deleted — marker retained, content cleared


Insert Text, Paragraphs, Tables, and Images at a Bookmark

Spire.Doc supports flexibly inserting various types of document elements at bookmark positions. It provides InsertText, InsertParagraph, and InsertTable methods for inserting text, paragraphs, and tables. Elements can also be inserted based on the index of the bookmark start node within the paragraph's ChildObjects collection.

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

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

    // Load fonts and Word file into VFS
    await window.spire.FetchFileToVFS('ARIAL.TTF', '/Library/Fonts/', `${process.env.PUBLIC_URL}/font/`);
    const inputFileName = 'BookmarkSample1.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Create a Document object and load the file
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Move to the bookmark position
    let navigator = new docModule.BookmarksNavigator(doc);
    navigator.MoveToBookmark("Bookmark1");

    // 1. Insert text
    navigator.InsertText("This is the inserted text content.", true);

    // 2. Insert paragraph
    let newParagraph = new docModule.Paragraph(doc);
    newParagraph.AppendText("This is the inserted paragraph content.")
    navigator.MoveToBookmark("Bookmark2");
    navigator.InsertParagraph(newParagraph);

    // 3. Insert table — 2 rows, 3 columns
    let table = new docModule.Table(doc, true);
    table.ResetCells(2, 3);
    table.Rows.get_Item(0).Cells.get_Item(0).AddParagraph().AppendText("Name");
    table.Rows.get_Item(0).Cells.get_Item(1).AddParagraph().AppendText("Quantity");
    table.Rows.get_Item(0).Cells.get_Item(2).AddParagraph().AppendText("Note");
    table.Rows.get_Item(1).Cells.get_Item(0).AddParagraph().AppendText("Product A");
    table.Rows.get_Item(1).Cells.get_Item(1).AddParagraph().AppendText("100");
    table.Rows.get_Item(1).Cells.get_Item(2).AddParagraph().AppendText("In Stock");

    navigator.MoveToBookmark("Bookmark3");
    navigator.InsertTable(table);

    // 4. Insert image
    const imageFileName = 'pic.png';
    await window.spire.FetchFileToVFS(imageFileName, '', `${process.env.PUBLIC_URL}/data/`);
    let picture = new docModule.DocPicture(doc);
    picture.LoadImage(imageFileName);
    picture.Width = 100;
    picture.Height = 200;

    navigator.MoveToBookmark("Bookmark4");
    // Get the bookmark start node
    let start = navigator.CurrentBookmark.BookmarkStart;
    // Get the paragraph containing the bookmark
    let bookmarkPara = start.OwnerParagraph;
    // Get the index of the bookmark start node in the paragraph
    let startIndex = bookmarkPara.ChildObjects.IndexOf(start);
    // Insert the image after the bookmark start node
    bookmarkPara.ChildObjects.Insert(startIndex + 1, picture);

    // Save as a .docx file
    const outputFileName = "InsertToBookmark.docx";

    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the generated file from VFS and trigger 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);

    // Release Document resources
    doc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Insert Elements at Bookmark Position</h1>
      <button onClick={insertElementsAtBookmark}>
        Generate
      </button>
    </div>
  );
}

export default App;

The figure below shows the generated document with text, paragraph, table, and image inserted at bookmark positions:

Text, paragraph, table, and image inserted at bookmark positions


FAQ

Formatting (font, size, color) is lost after replacing bookmark content — how to keep it?

ReplaceBookmarkContent replaces with plain text by default, discarding the original formatting. To preserve the bookmark's existing formatting, pass saveFormatting: true:

navigator.ReplaceBookmarkContent({ text: "New content", saveFormatting: true });

The replacement text will then inherit the original font, size, color, and other formatting from the bookmark.

How to batch process multiple bookmarks in a document?

Iterate through the doc.Bookmarks collection, locating and operating on each bookmark one by one:

for (let i = 0; i < doc.Bookmarks.Count; i++) {
    let bookmark = doc.Bookmarks.get_Item(i);
    navigator.MoveToBookmark(bookmark.Name);
    // Perform replace, delete, or insert operations
}

What's the difference between DeleteBookmarkContent and removing a bookmark marker?

  • DeleteBookmarkContent: Clears only the content within the bookmark range. The bookmark marker stays in the document, so you can still locate it by name and fill in new content later.
  • Bookmarks.Remove: Removes the bookmark marker itself. The content within the bookmark range is unaffected, but the bookmark name disappears and can no longer be located.

Choose the appropriate operation based on your needs: use DeleteBookmarkContent if you need to keep the "placeholder" capability, or remove the marker if the bookmark is no longer needed.

When inserting multiple elements at the same bookmark, why does only the last one take effect?

Methods like InsertText, InsertParagraph, and InsertTable insert based on the bookmark's current position. When inserting multiple times at the same bookmark, subsequent insertions may overwrite or shift previously inserted content. It is recommended to use separate bookmarks for each insertion, or re-locate the bookmark after each insert before proceeding with the next operation.


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.

A bookmark is like an invisible "anchor" in a Word document, able to accurately locate a specific position or selected text. Whether it's a fill-in area in a contract template, a key section to jump to in a long document, or a data insertion point when generating reports in batch, bookmarks are the critical anchor behind these operations. Developers can use bookmarks for dynamic content filling, navigation, content extraction, and other advanced features, making bookmark management one of the most commonly used capabilities in Word automation.

Spire.Doc for JavaScript runs entirely in the browser via WebAssembly, handling bookmark creation, navigation, and deletion directly — all managed through a virtual file system (VFS) with no backend server required.

This article covers three 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.


Add a Bookmark to a Paragraph

To add a bookmark in an existing document, use AppendBookmarkStart and AppendBookmarkEnd to mark the bookmark region on a paragraph. You can add bookmark markers to existing paragraphs or append a new paragraph with a bookmark. Spire.Doc also supports nested bookmarks for building hierarchical structures.

function App() {
  const createBookmarkInWord = 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 the Word file into VFS
    const inputFileName = 'ChinaTravelGuide.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Get the first section and add bookmarks
    let section = doc.Sections.get_Item(0);

    AddBookmark(section);

    // Save as a .docx file
    const outputFileName = "AddBookmark.docx";

    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the file from VFS and trigger 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);

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

  function AddBookmark(section) {
    // Bookmark 1: add bookmark markers around existing paragraphs
    let paraStart = section.Paragraphs.get_Item(1); 
    let paraEnd = section.Paragraphs.get_Item(3); 

    paraStart.AppendBookmarkStart("Bookmark1");  
    paraEnd.AppendBookmarkEnd("Bookmark1"); 

    // Bookmark 2: add a new paragraph with a bookmark
    let paragraph = section.AddParagraph(); 
    paragraph.AppendBookmarkStart("Bookmark2"); 
    paragraph.AppendText("This is a new paragraph");
    paragraph.AppendBookmarkEnd("Bookmark2"); 
  }

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Bookmark in Word</h1>
      <button onClick={createBookmarkInWord}>
        Generate
      </button>
    </div>
  );
}

export default App;

Bookmarks added to the generated Word document

Bookmarks added to the generated Word document


Add a Bookmark to Selected Text

To add a bookmark to specific text within an existing paragraph, first locate the text with FindAllString, create bookmark objects using the BookmarkStart and BookmarkEnd constructors, then insert the start marker before and the end marker after the matched TextRange via ChildObjects.Insert.

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

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

    // Load the Word file into VFS
    const inputFileName = 'ChinaTravelGuide.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Find all occurrences of "Street" in the document
    let textSelections = doc.FindAllString('Street', false, true);

    // Iterate over each match and insert bookmark start/end markers
    for (let i = 0; i < textSelections.length; i++) {

      // Create bookmark start and end objects (named "Bookmark_0", "Bookmark_1", ...)
      let start = new docModule.BookmarkStart(doc, "Bookmark_" + i);
      let end = new docModule.BookmarkEnd(doc, "Bookmark_" + i);

      let selection = textSelections[i];

      // Get the TextRange of the matched text
      let textRange = selection.GetAsOneRange();

      // Get the paragraph containing the matched text
      let para = textRange.OwnerParagraph;

      // Get the index of the TextRange within the paragraph's child objects
      let index = para.ChildObjects.IndexOf(textRange);

      // Insert the bookmark start before the TextRange and the bookmark end after it
      para.ChildObjects.Insert(index, start);
      para.ChildObjects.Insert(index + 2, end);
    }

    // Save as a new .docx file
    const outputFileName = "AddBookmark.docx";

    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the generated file from VFS and trigger 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);

    // Release document resources
    doc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Add Bookmarks for Specific Text in Word Documents</h1>
      <button onClick={addBookmarkForMatchedText}>
        Generate
      </button>
    </div>
  );
}

export default App;

This approach is ideal for scenarios where you need to add positioning markers on top of an existing document, such as marking fill-in areas in a completed contract. The figure below shows the result after execution:

Bookmarks added for specific text in the generated Word document


Remove a Bookmark

Removing a bookmark only removes the bookmark markers themselves — the text content within the bookmark range is preserved. Retrieve the bookmark object from the document.Bookmarks collection, then call the Remove method to delete it.

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

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

    // Load the Word file into VFS
    const inputFileName = 'AddBookmark.docx';
    await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);

    // Load the Word document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName);

    // Get the bookmark by name
    let bookmark = doc.Bookmarks.get_Item("Bookmark_1");

    // // Get the bookmark by index
    // let bookmark = doc.Bookmarks.get_Item(0);

    // Remove the bookmark (keep its content)
    doc.Bookmarks.Remove(bookmark);

    // Save as a new .docx file
    const outputFileName = "DeleteBookmark.docx";

    doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the generated file from VFS and trigger 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);

    // Release document resources
    doc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Delete Bookmark in Word Document</h1>
      <button onClick={deleteBookmark}>
        Generate
      </button>
    </div>
  );
}

export default App;

After the bookmark is removed, its markers disappear from the document, but the text within the bookmark range is preserved.

Document after bookmark markers are removed


FAQ

Duplicate bookmark name error

Cause: Bookmark names must be unique within a Word document. Adding a bookmark with a duplicate name causes an error.

Solution: Check whether the name already exists before adding the bookmark:

if (document.Bookmarks.FindByName("MyBookmark") === null) {
    paragraph.AppendBookmarkStart("MyBookmark");
    paragraph.AppendText("Content");
    paragraph.AppendBookmarkEnd("MyBookmark");
}

What is the difference between removing a bookmark and deleting its content?

Cause: Spire.Doc's Bookmarks.Remove only removes the bookmark markers (start and end), leaving the text content between them untouched.

Solution: Choose the appropriate operation based on your needs:

// Remove only the bookmark markers, keep the text
document.Bookmarks.Remove(bookmark);

// Remove the bookmark and its content (via BookmarksNavigator)
let navigator = new docModule.BookmarksNavigator(doc);
navigator.MoveToBookmark("MyBookmark");
navigator.DeleteBookmarkContent();

Do AppendBookmarkStart and AppendBookmarkEnd have to be on the same paragraph?

Cause: The start and end markers can be on different paragraphs — the "Bookmark1" example in the code above demonstrates cross-paragraph usage. The key constraint is that the document object structure within the bookmark range must remain intact. Bookmarks cannot span across table cells, since cells are independent containers and doing so may cause the bookmark to be unrecognized.

Solution: If the bookmark range crosses a table cell boundary, adjust the start or end position so that the bookmark closes within the same cell.


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.

page