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.

With Aspose.Words, you can 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.

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.

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-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateBookmark.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("MyBookmark");
builder.writeln("Text inside a bookmark.");
builder.endBookmark("MyBookmark");
builder.startBookmark("Nested Bookmark");
builder.writeln("Text inside a NestedBookmark.");
builder.endBookmark("Nested Bookmark");
builder.writeln("Text after Nested Bookmark.");
builder.endBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(1);
options.getOutlineOptions().setDefaultBookmarksOutlineLevel(2);
doc.save(dataDir + "output.pdf", options);
System.out.println("\nBookmark created successfully.");

Obtain Bookmarks

Sometimes it is necessary to obtain a bookmark collection to iterate through bookmarks or for other purposes. Use the Node.getRange 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-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
Bookmark bookmark1 = doc.getRange().getBookmarks().get(0);
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
doc.save(dataDir + "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);

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-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(BookmarkNameAndText.class);
Document doc = new Document(dataDir + "Bookmark.doc");
// Use the indexer of the Bookmarks collection to obtain the desired bookmark.
Bookmark bookmark = doc.getRange().getBookmarks().get("MyBookmark");
// Get the name and text of the bookmark.
String name = bookmark.getName();
String text = bookmark.getText();
// Set the name and text of the bookmark.
bookmark.setName("RenamedBookmark");
bookmark.setText("This is a new bookmarked text.");
System.out.println("\nBookmark name and text set successfully.");

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-Java
//Create empty document
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We call this method to start building the table.
builder.startTable();
builder.insertCell();
// Start bookmark here after calling InsertCell
builder.startBookmark("MyBookmark");
builder.write("Row 1, Cell 1 Content.");
// Build the second cell
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.endRow();
// Build the first cell of the second row.
builder.insertCell();
builder.write("Row 2, Cell 1 Content");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table.
builder.endTable();
//End of bookmark
builder.endBookmark("MyBookmark");
doc.save(dataDir + "output.doc");
System.out.println("\nTable bookmarked successfully.\nFile saved at " + dataDir);

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.

Note that some bookmarks in the document are assigned to form fields. Moving to such a bookmark and inserting text there inserts the text into the form field code. Although this will not invalidate the form field, the inserted text will not be visible because it becomes part of the field code.

The following code example shows how to access columns of the bookmarked table:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
// Create empty document
Document doc = new Document(dataDir + "Bookmark.Table_out.doc");
for (Bookmark bookmark : doc.getRange().getBookmarks())
{
System.out.printf("Bookmark: {0}{1}", bookmark.getName(), bookmark.isColumn() ? " (Column)" : "");
if (bookmark.isColumn())
{
Row row = (Row) bookmark.getBookmarkStart().getAncestor(NodeType.ROW);
if (row != null && bookmark.getFirstColumn() < row.getCells().getCount())
System.out.print(row.getCells().get(bookmark.getFirstColumn()).getText());
}
}

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 DocumentBuilder 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-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ShowHideBookmarks.class);
Document doc = new Document(dataDir + "Bookmark.doc");
showHideBookmarkedContent(doc,"MyBookmark",false);
doc.save(dataDir + "Updated_Document.docx");
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java
public static void showHideBookmarkedContent(Document doc, String bookmarkName, boolean showHide) throws Exception {
DocumentBuilder builder = new DocumentBuilder(doc);
Bookmark bm = doc.getRange().getBookmarks().get(bookmarkName);
builder.moveToDocumentEnd();
// {IF "{MERGEFIELD bookmark}" = "true" "" ""}
Field field = builder.insertField("IF \"", null);
builder.moveTo(field.getStart().getNextSibling().getNextSibling());
builder.insertField("MERGEFIELD " + bookmarkName + "", null);
builder.write("\" = \"true\" ");
builder.write("\"");
builder.write("\"");
builder.write(" \"\"");
Node currentNode = field.getStart();
boolean flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.RUN)
if (currentNode.toString(SaveFormat.TEXT).trim().equals("\""))
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkStart().getParentNode().insertBefore(currentNode, bm.getBookmarkStart());
currentNode = nextNode;
}
Node endNode = bm.getBookmarkEnd();
flag = true;
while (currentNode != null && flag) {
if (currentNode.getNodeType() == NodeType.FIELD_END)
flag = false;
Node nextNode = currentNode.getNextSibling();
bm.getBookmarkEnd().getParentNode().insertAfter(currentNode, endNode);
endNode = currentNode;
currentNode = nextNode;
}
doc.getMailMerge().execute(new String[]{bookmarkName}, new Object[]{showHide});
//In case, you do not want to use MailMerge then you may use the following lines of code.
//builder.moveToMergeField(bookmarkName);
//builder.write(showHide ? "true" : "false");
}