C++ Create, Read, and Delete Bookmarks in Word

A bookmark names a position or a region in a document and is commonly used for template placeholders, navigation targets, and batch content replacement. A bookmark is not displayed on the page and does not take part in layout; deleting a bookmark removes only the name and the markers, not the body text it covers. Bookmarks are therefore a suitable anchor when a program processes a document.

Spire.Doc for C++ creates bookmarks with Paragraph->AppendBookmarkStart() and Paragraph->AppendBookmarkEnd(), obtains the bookmark collection with Document->GetBookmarks(), and reads and deletes bookmarks with BookmarkCollection->FindByName(), GetItem(), and Remove(). All processing takes place in the local process, and the document does not need to be uploaded to any service.

This article covers three features:

The read and delete 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 create example works in a new, blank document and demonstrates a bookmark within one paragraph, nested bookmarks, and a cross-paragraph bookmark.

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.

Create Bookmarks

A bookmark consists of a start marker and an end marker, and the content between them belongs to the bookmark. AppendBookmarkStart() and AppendBookmarkEnd() are methods of Paragraph, so a bookmark can be created within a single paragraph, or its start and end markers can be placed in different paragraphs.

Operation Method
Create a start marker Paragraph->AppendBookmarkStart(name)
Create an end marker Paragraph->AppendBookmarkEnd(name)
Create nested bookmarks Call the end markers in "last opened, first closed" order
Create a cross-paragraph bookmark Call the start and end markers in two different paragraphs

The detailed steps are as follows.

  • Create a Document object and call AddSection() to add a section.
  • Add a title paragraph and set its character formatting.
  • Call AppendBookmarkStart() in a paragraph to start a simple bookmark, append text, and then call AppendBookmarkEnd() to end the bookmark.
  • Start Root, NestedLevel1, and NestedLevel2 in that order in the same paragraph, and then end the three bookmarks in reverse order.
  • Start CrossParagraph in one paragraph and end the bookmark in the next paragraph to form a cross-paragraph bookmark.
  • Save the result document with Document->SaveToFile().

The code for creating bookmarks 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/BookmarkStart.h"
#include "Spire/Doc/BookmarkEnd.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main() {

    //Create a Document object and add a section
    intrusive_ptr<Document> document = new Document();
    intrusive_ptr<Section> section = document->AddSection();

    intrusive_ptr<CharacterFormat> characterFormat = new CharacterFormat(document);
    characterFormat->SetFontName("Calibri");
    characterFormat->SetFontNameFarEast("Calibri");

    //Add a title paragraph
    intrusive_ptr<Paragraph> title = section->AddParagraph();
    intrusive_ptr<TextRange> titleRange = title->AppendText("Bookmark Creation Example");
    titleRange->GetCharacterFormat()->SetBold(true);
    titleRange->GetCharacterFormat()->SetFontSize(16);
    titleRange->GetCharacterFormat()->SetTextColor(Color::FromArgbRGB(31, 56, 100));
    titleRange->GetCharacterFormat()->SetFontName("Calibri");
    titleRange->GetCharacterFormat()->SetFontNameFarEast("Calibri");


    //Create a simple bookmark whose start and end markers are in the same paragraph
    intrusive_ptr<Paragraph> simple = section->AddParagraph();
    simple->AppendText("Simple bookmark: ")->ApplyCharacterFormat(characterFormat);
    simple->AppendBookmarkStart("SimpleBookmark");
    simple->AppendText("This text is inside the simple bookmark.")->ApplyCharacterFormat(characterFormat);
    simple->AppendBookmarkEnd("SimpleBookmark");

    //Create nested bookmarks and end them in reverse order
    intrusive_ptr<Paragraph> nested = section->AddParagraph();
    nested->AppendBookmarkStart("Root");
    nested->AppendText(" Root bookmark content ")->ApplyCharacterFormat(characterFormat);
    nested->AppendBookmarkStart("NestedLevel1");
    nested->AppendText(" Level 1 ")->ApplyCharacterFormat(characterFormat);
    nested->AppendBookmarkStart("NestedLevel2");
    nested->AppendText(" Level 2 ")->ApplyCharacterFormat(characterFormat);
    nested->AppendBookmarkEnd("NestedLevel2");
    nested->AppendBookmarkEnd("NestedLevel1");
    nested->AppendBookmarkEnd("Root");

    //Create a cross-paragraph bookmark with the markers in two paragraphs
    intrusive_ptr<Paragraph> crossStart = section->AddParagraph();
    crossStart->AppendBookmarkStart("CrossParagraph");
    crossStart->AppendText("The cross-paragraph bookmark starts in this paragraph, ")->ApplyCharacterFormat(characterFormat);
    intrusive_ptr<Paragraph> crossEnd = section->AddParagraph();
    crossEnd->AppendText("and ends in this paragraph.")->ApplyCharacterFormat(characterFormat);
    crossEnd->AppendBookmarkEnd("CrossParagraph");

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

In the new document, the simple bookmark covers a whole sentence, the nested bookmarks contain each other in the order Root → NestedLevel1 → NestedLevel2, and CrossParagraph extends from the third body paragraph to the fourth:

The simple, nested, and cross-paragraph bookmarks that were created

End Nested Bookmarks in Reverse Order

Nested bookmarks require the end order to be the reverse of the start order. Ending an outer bookmark before an inner one damages the bookmark ranges, and Word may correct or discard the abnormal markers. An end marker should refer to the name of its corresponding start marker and should lie within the range of the outer bookmark.

A Cross-Paragraph Bookmark Needs Markers in the Same Body Scope

AppendBookmarkStart() and AppendBookmarkEnd() act on two paragraphs separately, so a cross-paragraph bookmark is permitted. CrossParagraph in the example starts in the third body paragraph and ends in the fourth. When a bookmark crosses a table boundary, confirm that the start and end markers are in paragraphs or cells of the same body scope, so that the bookmark range is not cut off by the table structure.

Bookmark Names Must Follow the Naming Rules

A bookmark name must begin with a letter, may contain letters, digits, and underscores, cannot contain spaces, and cannot exceed 40 characters. A name should be unique within the document. If a bookmark is created with a duplicate name, the object returned when reading or deleting by that name may not be the intended bookmark.

Read Bookmarks

Document->GetBookmarks() returns the collection of bookmarks in the document, of type BookmarkCollection. The bookmarks in the collection are ordered by their position in the body and can be traversed by index, or a single bookmark can be found by name. Bookmark->GetName() returns the bookmark name, BookmarkCollection->GetItem(index) reads a bookmark by index, and BookmarkCollection->FindByName(name) reads a bookmark by name.

Operation Method
Read all bookmarks Document->GetBookmarks()
Get the bookmark count BookmarkCollection->GetCount()
Read by index BookmarkCollection->GetItem(index)
Read by name BookmarkCollection->FindByName(name)
Read the bookmark name Bookmark->GetName()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Call Document->GetBookmarks() to obtain the bookmark collection, and print the bookmark count.
  • Traverse the collection by index with GetItem() and print each bookmark name.
  • Call FindByName() to read ScopePhase, and then use GetItem() to read the last bookmark in the collection.
  • Close the document.

The code for reading bookmarks 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/Collections/BookmarkCollection.h"
#include "Spire/Doc/Bookmark.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;

int main() {

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

    //Read all bookmarks and print their names
    intrusive_ptr<BookmarkCollection> bookmarks = document->GetBookmarks();
    cout << "Bookmark count: " << bookmarks->GetCount() << endl;
    for (int i = 0; i < bookmarks->GetCount(); i++)
    {
        intrusive_ptr<Bookmark> bookmark = bookmarks->GetItem(i);
        cout << i << "  " << bookmark->GetName() << endl;
    }

    //Read a bookmark by name
    intrusive_ptr<Bookmark> scopePhase = bookmarks->FindByName("ScopePhase");
    cout << "By name: " << scopePhase->GetName() << endl;

    //Read a bookmark by index
    intrusive_ptr<Bookmark> last = bookmarks->GetItem(bookmarks->GetCount() - 1);
    cout << "By index: " << last->GetName() << endl;

    document->Close();
    return 0;
}

The nine bookmarks in the template are printed in body order, and FindByName() and GetItem() obtain ScopePhase and the last bookmark, SignDate, respectively. The console output is as follows:

Bookmark count: 9
0  PartyA
1  PartyB
2  ServiceScope
3  ScopePhase
4  AddendumAnchor
5  Budget
6  PaymentTerms
7  SealAnchor
8  SignDate
By name: ScopePhase
By index: SignDate

Collection Indexes Follow Body Order

The elements of BookmarkCollection are ordered by the position of the bookmarks in the body. A nested bookmark also occupies one place in the collection: ScopePhase appears after the start marker of ServiceScope, so it is at index 3 in the example. After the document is edited, indexes may change, and reading by name is usually more stable than reading by index.

Verify the Bookmark Name Before Reading

FindByName() performs an exact lookup by name. Before calling it, confirm that the spelling matches the actual name in the document. If the name does not exist, no valid bookmark object is returned, and subsequent name reads or delete operations cannot complete. When a name is long or generated by a program, traverse the collection and print the names first, then construct the lookup argument from the result.

Reading Bookmarks Does Not Modify the Body

Reading bookmarks accesses only bookmark names and markers; it does not change the body content or the layout of the document. The example closes the document after reading and performs no save operation. When other changes made during reading need to be kept, call SaveToFile().

Delete Bookmarks

BookmarkCollection->Remove(bookmark) deletes a specified bookmark, and the parameter is a Bookmark object obtained through FindByName() or GetItem(). Deletion removes only the bookmark name and the start and end markers; the body text, character formatting, and paragraph formatting covered by the bookmark remain unchanged.

Operation Method
Find a bookmark by name BookmarkCollection->FindByName(name)
Delete a bookmark BookmarkCollection->Remove(bookmark)
Read the count after deletion Document->GetBookmarks()->GetCount()

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Call Document->GetBookmarks() to obtain the bookmark collection.
  • Call FindByName() to obtain the PaymentTerms bookmark.
  • Call Remove() to delete the bookmark, and print the bookmark count after deletion.
  • Save the result document with Document->SaveToFile().

The code for deleting a bookmark 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/Collections/BookmarkCollection.h"
#include "Spire/Doc/Bookmark.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;

int main() {

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

    //Find and remove the bookmark by name; the body text is left unchanged
    intrusive_ptr<BookmarkCollection> bookmarks = document->GetBookmarks();
    intrusive_ptr<Bookmark> target = bookmarks->FindByName("PaymentTerms");
    bookmarks->Remove(target);
    cout << "Count after removal: " << document->GetBookmarks()->GetCount() << endl;

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

After PaymentTerms is deleted, the bookmark count changes from 9 to 8, and the console output is as follows:

Count after removal: 8

The payment plan paragraph in the document keeps its original text and centered formatting and lacks only the bookmark markers:

The body text is unchanged after the PaymentTerms bookmark is removed

Deleting a Bookmark Is Not the Same as Deleting Content

BookmarkCollection->Remove() deletes only the bookmark name and markers, and the body text remains unchanged. After the example deletes PaymentTerms, the placeholder text in the document is still present. To delete the content covered by a bookmark, use BookmarksNavigator->DeleteBookmarkContent(), or obtain the indexes of the start and end markers and remove the objects between them.

Deleting a Bookmark Does Not Update References

Deleting a bookmark modifies only the bookmark collection and does not update references to the bookmark in a table of contents, a cross-reference, or a header or footer. If the bookmark is referenced by a field elsewhere in the document, traverse the relevant fields and call Field->Update() after deletion, or re-establish the reference.

Duplicate Names Affect Deletion by Name

Bookmark names should be unique within a document. When a duplicate name exists, the object returned by FindByName() may not be the intended bookmark, and Remove() deletes only one of them. Before batch processing, traverse the collection and check the names and positions to confirm the bookmark object to delete.

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.