C++ Extract, Copy, and Replace Bookmark Content in Word

The content of a bookmark is not a string but a region made up of paragraphs, tables, and other body objects. When reading, copying, or replacing bookmark content, these objects need to be carried in a TextBodyPart rather than treating the bookmark as ordinary text. BookmarksNavigator provides the entry points for locating a bookmark, obtaining its content, and replacing its content, and the extract and copy operations can preserve the paragraph formatting and character formatting within the bookmark range.

Spire.Doc for C++ locates a bookmark with BookmarksNavigator->MoveToBookmark(), obtains a TextBodyPart with GetBookmarkContent(), writes content into the target document body with TextBodyPart->PasteAtEnd(), and replaces a bookmark range with plain text or complex content with ReplaceBookmarkContent(). All processing takes place in the local process, and the document does not need to be uploaded to any service.

This article covers four features:

The examples use the "Warehouse Scheduling System Implementation Service Agreement" template (ServiceAgreement.docx). The document has two pages and contains nine bookmarks, of which ScopePhase is nested inside ServiceScope:

Bookmark Position Purpose
PartyA Parties section Party A name
PartyB Parties section Party B name
ServiceScope Section 2 Service scope spanning three body objects
ScopePhase Paragraph of item (1) in Section 2 (nested in ServiceScope) Stage name
AddendumAnchor End of Section 2 Insertion point for the appendix body
Budget Section 4 Contract amount
PaymentTerms Section 5 Payment plan placeholder paragraph
SealAnchor Party A cell of the signature table Insertion point for the seal image
SignDate Party A date in the signature table Signing date

The extract and copy examples process the ServiceScope bookmark, and the replace examples process the PartyB, Budget, SignDate, and PaymentTerms bookmarks.

Service agreement template containing nine bookmarks

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Extract Bookmark Content

BookmarksNavigator->MoveToBookmark(name) moves the locator to the specified bookmark, and GetBookmarkContent() returns the content within the bookmark range as a TextBodyPart. The GetBodyItems() collection of TextBodyPart holds the paragraphs and tables covered by the bookmark; after checking DocumentObject->GetDocumentObjectType() for each item, the paragraph text can be read or the item can be handled as a table.

Operation Method
Locate a bookmark BookmarksNavigator->MoveToBookmark(name)
Obtain the bookmark content BookmarksNavigator->GetBookmarkContent()
Traverse the body objects TextBodyPart->GetBodyItems()
Identify the object type DocumentObject->GetDocumentObjectType()
Read the paragraph text Paragraph->GetText()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object and call MoveToBookmark() to locate ServiceScope.
  • Call GetBookmarkContent() to obtain the TextBodyPart, and print the body item count.
  • Traverse GetBodyItems() and call GetText() on objects of the paragraph type to print their text.
  • Close the document.

The code for extracting bookmark content is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/TextBodyPart.h"
#include "Spire/Doc/Collections/BodyRegionCollection.h"
#include "Spire/Doc/Collections/DocumentObjectCollection.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/DocumentObjectType.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");

    //Locate the ServiceScope bookmark and obtain its content
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("ServiceScope");
    intrusive_ptr<TextBodyPart> part = navigator->GetBookmarkContent();

    //Traverse the body objects in the bookmark range and print the paragraph text
    cout << "Body item count: " << part->GetBodyItems()->GetCount() << endl;
    for (int i = 0; i < part->GetBodyItems()->GetCount(); i++)
    {
        intrusive_ptr<DocumentObject> item = part->GetBodyItems()->GetItem(i);
        if (item->GetDocumentObjectType() == DocumentObjectType::Paragraph)
        {
            intrusive_ptr<Paragraph> paragraph = Object::Dynamic_cast<Paragraph>(item);
            cout << paragraph->GetText() << endl;
        }
    }

    document->Close();
    return 0;
}

ServiceScope starts at the introductory paragraph of Section 2 and ends at the paragraph of item (2), "System Implementation and Go-Live Support", covering three body objects. The console output is as follows:

Body item count: 3
Party B shall provide Party A with implementation and maintenance support for the warehouse scheduling system as agreed in this Agreement. The scope covers the following two stages.
(1) Project Kickoff and Requirements Research: Party B shall assign an implementation team on site to survey the current warehouse operations, analyze processes, and confirm requirements, produce the Requirements Specification, and obtain Party A’s written confirmation.
(2) System Implementation and Go-Live Support: deploy the scheduling system environment, conduct interface integration testing, migrate data, and run trials, and provide three months of maintenance support after go-live.

Body Item Count Includes Paragraphs and Tables

GetBodyItems() returns the body objects within the bookmark range; paragraphs, tables, and empty paragraphs are each counted. In the example, ServiceScope covers three paragraphs, so the count is 3. A bookmark range can span paragraphs; when reading text, check the type of each item and do not assume that the collection contains only paragraphs. When processing by paragraph index, filter the members of DocumentObjectType::Paragraph first and then renumber them.

The Collection May Contain Tables

If a bookmark covers a table, GetBodyItems() returns a table object. Calling Object::Dynamic_cast<Paragraph>() directly does not obtain a paragraph in that case; check GetDocumentObjectType() first and then decide whether to handle the item as a table or as a paragraph. When a bookmark is located in a table cell, the hierarchy of body objects also includes cells, rows, and the table.

Extraction Does Not Modify the Document

Extracting bookmark content only reads body objects and prints text; it does not change the document structure. The example closes the document after reading and performs no save operation. When the extracted result needs to be kept as a document, call PasteAtEnd() after obtaining the TextBodyPart, or write the paragraph text into a new document directly.

Copy Bookmark Content to a New Document

TextBodyPart->PasteAtEnd(body) appends the body objects within the bookmark range to the end of the target body. During pasting, paragraph formatting and character formatting are copied with the content, so the font, font size, line spacing, and first-line indent in the target document match those of the source document.

Operation Method
Obtain the bookmark content BookmarksNavigator->GetBookmarkContent()
Paste into the target body TextBodyPart->PasteAtEnd(body)
Obtain the target body Section->GetBody()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object and call MoveToBookmark() to locate ServiceScope.
  • Call GetBookmarkContent() to obtain the TextBodyPart.
  • Create a new document and section, and call PasteAtEnd() to copy the bookmark content into the body of the new document.
  • Save the copied result with Document->SaveToFile().

The code for copying bookmark content is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Body.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/TextBodyPart.h"
#include "Spire/Doc/Collections/BodyRegionCollection.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");

    //Locate the ServiceScope bookmark and obtain its content
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("ServiceScope");
    intrusive_ptr<TextBodyPart> part = navigator->GetBookmarkContent();

    //Copy the bookmark content to a new document, keeping the paragraph formatting
    intrusive_ptr<Document> copy = new Document();
    intrusive_ptr<Section> section = copy->AddSection();
    part->PasteAtEnd(section->GetBody());
    cout << "Body items copied to the new document: " << part->GetBodyItems()->GetCount() << endl;

    //Save the new document as docx
    copy->SaveToFile("Output/ExtractedScope.docx", FileFormat::Docx);
    copy->Close();
    document->Close();
    return 0;
}

The console output is as follows:

Body items copied to the new document: 3

After the content is copied to the new document, the three paragraphs retain their font, font size, and line spacing:

The ServiceScope bookmark content copied to the new document

Copied Content Retains Paragraph Formatting

PasteAtEnd() writes the objects in the TextBodyPart into the target body and preserves paragraph formatting and character formatting. In the example, after the bookmark content is copied to a new document, the font, line spacing, and first-line indent match the template. If the target document needs its own page setup, adjust the section margins or paper orientation after pasting.

Cross-Document Copying Should Go Through TextBodyPart

For cross-document copying, obtain the TextBodyPart of the bookmark content first and then call PasteAtEnd() to write it into the target document. Calling TextBodyPart::Copy() on paragraphs in the source document directly may return an empty collection in a cross-document scenario, and Clone() may also fail. The example uses the "extract, then paste" path, so both the content and the formatting come from the source bookmark.

Hierarchy When the Bookmark Is in a Table

If a bookmark is located in a table cell, the owner hierarchy of the start and end markers includes cells, rows, and the table. The body objects returned by GetBookmarkContent() may then include the table; when copying or reading, check the type of the outermost object first and then decide whether to handle it as a table or as a paragraph. The table width and column widths in the target document need to be adjusted separately according to the page width.

Replace Bookmark Content with Plain Text

ReplaceBookmarkContent(text, saveFormatting) replaces the content within the bookmark range with a string. The replacement applies to the bookmark range, and text outside the bookmark remains unchanged. The second parameter, saveFormatting, specifies whether to retain the original formatting of the bookmark: when false is passed, the default character formatting of the new text is used; when true is passed, the character formatting of the bookmark content is retained.

Operation Method
Replace with plain text ReplaceBookmarkContent(text, saveFormatting)
Replace with complex content ReplaceBookmarkContent(TextBodyPart)
Delete the bookmark content DeleteBookmarkContent(saveFormatting)
Retain the original bookmark formatting The saveFormatting parameter

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object.
  • Locate PartyB, Budget, and SignDate in turn, and call ReplaceBookmarkContent() to write the new values.
  • Save the result document with Document->SaveToFile().

The code for replacing bookmark content with plain text is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);

    //Replace the content of three bookmarks with plain text
    navigator->MoveToBookmark("PartyB");
    navigator->ReplaceBookmarkContent("Qicheng Supply Chain Co., Ltd.", false);

    navigator->MoveToBookmark("Budget");
    navigator->ReplaceBookmarkContent("¥ 520,000", false);

    navigator->MoveToBookmark("SignDate");
    navigator->ReplaceBookmarkContent("December 8, 2026", false);

    //Save the document as docx
    document->SaveToFile("Output/FilledAgreementText.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The replacement results for the three bookmarks are as follows:

Bookmark Before After
PartyB Hongyuan Logistics Co., Ltd. Qicheng Supply Chain Co., Ltd.
Budget ¥ 480,000 ¥ 520,000
SignDate December 1, 2026 December 8, 2026

After PartyB is replaced, the Party B name on the first page of the agreement changes from Hongyuan Logistics Co., Ltd. to Qicheng Supply Chain Co., Ltd.:

The first page of the agreement after the PartyB bookmark is replaced

After Budget is replaced, the contract amount in Section 4 changes from ¥ 480,000 to ¥ 520,000:

The contract amount after the Budget bookmark is replaced

After SignDate is replaced, the Party A date in the signature table changes from December 1, 2026 to December 8, 2026, while the Party B date remains unchanged:

The signing date after the SignDate bookmark is replaced

The saveFormatting Parameter Controls the Formatting Source

The second parameter of ReplaceBookmarkContent(text, saveFormatting) specifies whether to retain the original formatting of the bookmark. The example passes false, so the replaced text uses the default character formatting of the new text; when true is passed, the character formatting of the bookmark content is retained. When the new value needs to match the style of the template, set the character formatting explicitly for the replacement content, or switch to a TextBodyPart and pass content that already carries the formatting.

Replacement Applies Only to the Bookmark Range

A replace operation modifies only the content within the bookmark range, and the text before and after the bookmark remains unchanged. In the example, after Budget is replaced, the phrases "The total amount of this Agreement is RMB" and "(tax inclusive)" around the amount are still present. When the bookmark range covers several paragraphs, confirm that the paragraph structure after replacement meets expectations before saving the result document.

The Bookmark Is Retained After Replacement

ReplaceBookmarkContent() replaces the content within the bookmark range, and the bookmark name and markers still exist. After the example replaces three bookmarks, all nine bookmarks in the document are retained, and they can be located by name and replaced again later. To clear the bookmark content while keeping the placeholder paragraph, use BookmarksNavigator->DeleteBookmarkContent(); to delete the bookmark while keeping the body text, use BookmarkCollection->Remove().

Replace Bookmark Content with a Table

ReplaceBookmarkContent(TextBodyPart) replaces the bookmark range with complex content such as paragraphs and tables. The example replaces the payment placeholder paragraph PaymentTerms with a four-row, three-column payment table. The table is added to the TextBodyPart through TextBodyPart->GetBodyItems()->Add(table) and then passed to ReplaceBookmarkContent().

Operation Method
Create a table new Table(document, true)
Build the row and column structure Table->ResetCells(rows, columns)
Obtain a cell Table->GetRows()->GetItem(r)->GetCells()->GetItem(c)
Add content to the body part TextBodyPart->GetBodyItems()->Add(table)
Replace the bookmark ReplaceBookmarkContent(part)

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object.
  • Create a Table object and call ResetCells() to build a four-row, three-column structure.
  • Call AddParagraph() for the header cells to add paragraphs, and set bold text, white text, and dark blue shading.
  • Fill the data rows with the payment stage, ratio, and payment time.
  • Add the table to the TextBodyPart, locate PaymentTerms, and call ReplaceBookmarkContent(part) to replace the placeholder paragraph.
  • Save the result document with Document->SaveToFile().

The code for replacing bookmark content with a table is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/TextBodyPart.h"
#include "Spire/Doc/Collections/BodyRegionCollection.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/CellFormat.h"
#include "Spire/Doc/Fields/Shapes/Shading.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);

    //Build the payment table that replaces the PaymentTerms bookmark
    intrusive_ptr<Table> table = new Table(document, true);
    table->ResetCells(4, 3);
    const char* headers[3] = {"Payment Stage", "Ratio", "Payment Time"};
    for (int c = 0; c < 3; c++)
    {
        intrusive_ptr<TableCell> cell = table->GetRows()->GetItem(0)->GetCells()->GetItem(c);
        intrusive_ptr<Paragraph> paragraph = cell->AddParagraph();
        paragraph->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
        intrusive_ptr<TextRange> range = paragraph->AppendText(headers[c]);
        range->GetCharacterFormat()->SetBold(true);
        range->GetCharacterFormat()->SetTextColor(Color::GetWhite());
        cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
            Color::FromArgbRGB(31, 56, 100));
    }

    const char* rows[3][3] = {
        {"Down Payment", "20%", "Within 10 business days after the Agreement takes effect"},
        {"Go-Live Payment", "50%", "After the system goes live and Party A confirms"},
        {"Final Payment", "30%", "Within 15 business days after project acceptance"}};
    for (int r = 0; r < 3; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            intrusive_ptr<TableCell> cell = table->GetRows()->GetItem(r + 1)->GetCells()->GetItem(c);
            intrusive_ptr<Paragraph> paragraph = cell->AddParagraph();
            paragraph->GetFormat()->SetHorizontalAlignment(
                c == 0 ? HorizontalAlignment::Center : HorizontalAlignment::Left);
            paragraph->AppendText(rows[r][c]);
        }
    }

    //Replace the PaymentTerms bookmark with the table
    intrusive_ptr<TextBodyPart> part = new TextBodyPart(document);
    part->GetBodyItems()->Add(table);
    navigator->MoveToBookmark("PaymentTerms");
    navigator->ReplaceBookmarkContent(part);

    //Save the document as docx
    document->SaveToFile("Output/FilledAgreementTable.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The paragraph that contained PaymentTerms is replaced by the four-row, three-column payment table, and the header uses the same dark blue shading as the agreement template:

The payment plan after the PaymentTerms bookmark is replaced with a table

Cells Have No Default Paragraph After ResetCells

Table->ResetCells(rows, columns) creates only the row and column structure, and the cells contain no ready-made paragraph. Before filling content, call TableCell->AddParagraph() to add a paragraph and then call Paragraph->AppendText() to write the text. Using GetParagraphs()->GetItem(0) directly may obtain an empty collection and cause the program to fail.

Empty Paragraphs May Remain After Table Replacement

When a bookmark is replaced with a TextBodyPart, the table is inserted at the bookmark position, and the paragraph that contained the bookmark may remain as a blank paragraph. In the example, one empty paragraph remains before and after the payment table. When a compact layout is required, traverse the body objects after replacement and delete empty paragraphs that contain no text.

Table Style Must Be Set Explicitly

A replacement table does not inherit the borders and shading of other tables in the template. The example sets only the header shading, bold text, and white text, and the data rows use the default borders. To match the tables in the template, set the cell borders, background color, and column widths through CellFormat and Shading.

Get a Free License

If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.