Working with Bookmarks

Bookmarks identify in a Microsoft Word document the locations or fragments that you name and identify for future reference. For example, you might use a bookmark to identify text that you want to revise later. Instead of scrolling through the document to locate the text, you can go to it by using the Bookmark dialog box.

The actions that can be performed with bookmarks using Aspose.Words are the same as the ones you can perform using Microsoft Word. You can insert a new bookmark, delete, move to a bookmark, get or set a bookmark name, get or set text enclosed in it. With Aspose.Words, you can also use bookmarks in reports or documents to insert some data into the bookmark or apply special formatting to its content. You can also use bookmarks to retrieve text from a certain location in your document.

Insert a Bookmark

Use StartBookmark and EndBookmark to create a bookmark by marking its start and end, respectively. Do not forget to pass the same bookmark name to both methods. Bookmarks in a document can overlap and span any range. Badly formed bookmarks or bookmarks with duplicate names will be ignored when the document is saved.

The following code example shows how to create a new bookmark:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String outputDataDir = GetOutputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
builder->StartBookmark(u"My Bookmark");
builder->Writeln(u"Text inside a bookmark.");
builder->StartBookmark(u"Nested Bookmark");
builder->Writeln(u"Text inside a NestedBookmark.");
builder->EndBookmark(u"Nested Bookmark");
builder->Writeln(u"Text after Nested Bookmark.");
builder->EndBookmark(u"My Bookmark");
System::SharedPtr<PdfSaveOptions> options = System::MakeObject<PdfSaveOptions>();
options->get_OutlineOptions()->get_BookmarksOutlineLevels()->Add(u"My Bookmark", 1);
options->get_OutlineOptions()->get_BookmarksOutlineLevels()->Add(u"Nested Bookmark", 2);
System::String outputPath = outputDataDir + u"CreateBookmark.pdf";
doc->Save(outputPath, options);

Obtain Bookmarks

Sometimes it is necessary to obtain a bookmark collection to iterate through bookmarks or for other purposes. Use the Node.Range property exposed by any document node that returns a Range object representing the portion of the document contained in this node. Use this object to retrieve a BookmarkCollection and then use the collection indexer to get a specific bookmark.

The following code example shows how to obtain bookmarks from a bookmark collection:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Bookmarks.doc");
// By index.
System::SharedPtr<Bookmark> bookmark1 = doc->get_Range()->get_Bookmarks()->idx_get(0);
// By name.
System::SharedPtr<Bookmark> bookmark2 = doc->get_Range()->get_Bookmarks()->idx_get(u"Bookmark2");

The following code example shows how to get or set a bookmark name and text:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
System::SharedPtr<Bookmark> bookmark = doc->get_Range()->get_Bookmarks()->idx_get(u"MyBookmark");
// Get the name and text of the bookmark.
System::String name = bookmark->get_Name();
System::String text = bookmark->get_Text();
// Set the name and text of the bookmark.
bookmark->set_Name(u"RenamedBookmark");
bookmark->set_Text(u"This is a new bookmarked text.");

The following code example shows how to bookmark a table:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
// Create empty document
System::SharedPtr<Document> doc = System::MakeObject<Document>();
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Table> table = builder->StartTable();
// Insert a cell
builder->InsertCell();
// Start bookmark here after calling InsertCell
builder->StartBookmark(u"MyBookmark");
builder->Write(u"This is row 1 cell 1");
// Insert a cell
builder->InsertCell();
builder->Write(u"This is row 1 cell 2");
builder->EndRow();
// Insert a cell
builder->InsertCell();
builder->Writeln(u"This is row 2 cell 1");
// Insert a cell
builder->InsertCell();
builder->Writeln(u"This is row 2 cell 2");
builder->EndRow();
builder->EndTable();
// End of bookmark
builder->EndBookmark(u"MyBookmark");
System::String outputPath = outputDataDir + u"BookmarkTable.doc";
doc->Save(outputPath);

If you change the name of a bookmark to a name that already exists in the document, no error will be generated and only the first bookmark will be stored when you save the document.

Move to a Bookmark

If you need to insert rich content (not just plain text) into a bookmark, you should use MoveToBookmark to move the cursor to the bookmark and then use the DocumentBuilder’s methods and properties to insert content.

Show Hide Bookmark Content

The entire Bookmark (including the bookmarked content) can be encapsulated within the True part of the IF field using Aspose.Words. It can be in such a way that the IF field contains a nested Merge Field in the expression (Left of Operator) and depending upon the value of Merge Field, the IF field shows or hides the content of Bookmark in Word Document.

The following code example shows how to show/ hide bookmarks:

For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C
typedef System::SharedPtr<System::Object> TObjectPtr;
System::String bookmarkName = u"Bookmark2";
// The path to the documents directory.
System::String inputDataDir = GetInputDataDir_WorkingWithBookmarks();
System::String outputDataDir = GetOutputDataDir_WorkingWithBookmarks();
System::SharedPtr<Document> doc = System::MakeObject<Document>(inputDataDir + u"Bookmarks.doc");
System::SharedPtr<DocumentBuilder> builder = System::MakeObject<DocumentBuilder>(doc);
System::SharedPtr<Bookmark> bm = doc->get_Range()->get_Bookmarks()->idx_get(bookmarkName);
builder->MoveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
System::SharedPtr<Field> field = builder->InsertField(u"IF \"", nullptr);
builder->MoveTo(field->get_FieldStart()->get_NextSibling());
builder->InsertField(System::String(u"MERGEFIELD ") + bookmarkName + u"", nullptr);
builder->Write(u"\" = \"true\" ");
builder->Write(u"\"");
builder->Write(u"\"");
builder->Write(u" \"\"");
System::SharedPtr<Node> currentNode = field->get_FieldStart();
bool flag = true;
while (currentNode != nullptr && flag)
{
if (currentNode->get_NodeType() == Aspose::Words::NodeType::Run)
{
if (System::ObjectExt::Equals(currentNode->ToString(Aspose::Words::SaveFormat::Text).Trim(), u"\""))
{
flag = false;
}
}
System::SharedPtr<Node> nextNode = currentNode->get_NextSibling();
bm->get_BookmarkStart()->get_ParentNode()->InsertBefore(currentNode, bm->get_BookmarkStart());
currentNode = nextNode;
}
System::SharedPtr<Node> endNode = bm->get_BookmarkEnd();
flag = true;
while (currentNode != nullptr && flag)
{
if (currentNode->get_NodeType() == Aspose::Words::NodeType::FieldEnd)
{
flag = false;
}
System::SharedPtr<Node> nextNode = currentNode->get_NextSibling();
bm->get_BookmarkEnd()->get_ParentNode()->InsertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc->get_MailMerge()->Execute(System::MakeArray<System::String>({bookmarkName}), System::MakeArray<TObjectPtr>({System::ObjectExt::Box<bool>(false)}));
//MailMerge can be avoided by using the following
//builder.MoveToMergeField(bookmarkName);
//builder.Write(showHide ? "true" : "false");
doc->Save(outputDataDir + u"Updated_Document_out.doc");