com.aspose.words

Class Bookmark

  • java.lang.Object
    • com.aspose.words.Bookmark
public class Bookmark 
extends java.lang.Object

Represents a single bookmark.

Bookmark is a "facade" object that encapsulates two nodes BookmarkStart and BookmarkEnd in a document tree and allows to work with a bookmark as a single object.

Example:

Shows how to add bookmarks and update their contents.
public void createUpdateAndPrintBookmarks() throws Exception
{
    // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
    Document doc = createDocumentWithBookmarks(3);
    BookmarkCollection bookmarks = doc.getRange().getBookmarks();

    printAllBookmarkInfo(bookmarks);

    // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
    bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
    bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");

    // Print all bookmarks again to see updated values.
    printAllBookmarkInfo(bookmarks);
}

/// <summary>
/// Create a document with a given number of bookmarks.
/// </summary>
private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception
{
    Document doc = new Document();
    DocumentBuilder builder = new DocumentBuilder(doc);

    for (int i = 1; i <= numberOfBookmarks; i++)
    {
        String bookmarkName = "MyBookmark_" + i;

        builder.write("Text before bookmark.");
        builder.startBookmark(bookmarkName);
        builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
        builder.endBookmark(bookmarkName);
        builder.writeln("Text after bookmark.");
    }

    return doc;
}

/// <summary>
/// Use an iterator and a visitor to print info of every bookmark in the collection.
/// </summary>
private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception
{
    BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();

    // Get each bookmark in the collection to accept a visitor that will print its contents.
    Iterator<Bookmark> enumerator = bookmarks.iterator();

    while (enumerator.hasNext()) {
        Bookmark currentBookmark = enumerator.next();

            if (currentBookmark != null)
            {
            currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
            currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);

            System.out.println(currentBookmark.getBookmarkStart().getText());
        }
    }
}

/// <summary>
/// Prints contents of every visited bookmark to the console.
/// </summary>
public static class BookmarkInfoPrinter extends DocumentVisitor {
    public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
        System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                bookmarkStart.getBookmark().getText()));
        return VisitorAction.CONTINUE;
    }

    public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
        System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
        return VisitorAction.CONTINUE;
    }
}

Property Getters/Setters Summary
BookmarkEndgetBookmarkEnd()
Gets the node that represents the end of the bookmark.
BookmarkStartgetBookmarkStart()
Gets the node that represents the start of the bookmark.
intgetFirstColumn()
Gets the zero-based index of the first column of the table column range associated with the bookmark.
booleanisColumn()
Returns true if this bookmark is a table column bookmark.
intgetLastColumn()
Gets the zero-based index of the last column of the table column range associated with the bookmark.
java.lang.StringgetName()
void
setName(java.lang.Stringvalue)
           Gets or sets the name of the bookmark.
java.lang.StringgetText()
void
setText(java.lang.Stringvalue)
           Gets or sets the text enclosed in the bookmark.
 
Method Summary
voidremove()
Removes the bookmark from the document. Does not remove text inside the bookmark.
 

    • Property Getters/Setters Detail

      • getBookmarkEnd

        public BookmarkEnd getBookmarkEnd()
        
        Gets the node that represents the end of the bookmark.

        Example:

        Shows how to add bookmarks and update their contents.
        public void createUpdateAndPrintBookmarks() throws Exception
        {
            // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
            Document doc = createDocumentWithBookmarks(3);
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            printAllBookmarkInfo(bookmarks);
        
            // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
            bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
            bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");
        
            // Print all bookmarks again to see updated values.
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with a given number of bookmarks.
        /// </summary>
        private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            for (int i = 1; i <= numberOfBookmarks; i++)
            {
                String bookmarkName = "MyBookmark_" + i;
        
                builder.write("Text before bookmark.");
                builder.startBookmark(bookmarkName);
                builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
                builder.endBookmark(bookmarkName);
                builder.writeln("Text after bookmark.");
            }
        
            return doc;
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark in the collection.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception
        {
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get each bookmark in the collection to accept a visitor that will print its contents.
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                    if (currentBookmark != null)
                    {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Prints contents of every visited bookmark to the console.
        /// </summary>
        public static class BookmarkInfoPrinter extends DocumentVisitor {
            public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
                System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                        bookmarkStart.getBookmark().getText()));
                return VisitorAction.CONTINUE;
            }
        
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
                System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
                return VisitorAction.CONTINUE;
            }
        }
      • getBookmarkStart

        public BookmarkStart getBookmarkStart()
        
        Gets the node that represents the start of the bookmark.

        Example:

        Shows how to add bookmarks and update their contents.
        public void createUpdateAndPrintBookmarks() throws Exception
        {
            // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
            Document doc = createDocumentWithBookmarks(3);
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            printAllBookmarkInfo(bookmarks);
        
            // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
            bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
            bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");
        
            // Print all bookmarks again to see updated values.
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with a given number of bookmarks.
        /// </summary>
        private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            for (int i = 1; i <= numberOfBookmarks; i++)
            {
                String bookmarkName = "MyBookmark_" + i;
        
                builder.write("Text before bookmark.");
                builder.startBookmark(bookmarkName);
                builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
                builder.endBookmark(bookmarkName);
                builder.writeln("Text after bookmark.");
            }
        
            return doc;
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark in the collection.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception
        {
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get each bookmark in the collection to accept a visitor that will print its contents.
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                    if (currentBookmark != null)
                    {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Prints contents of every visited bookmark to the console.
        /// </summary>
        public static class BookmarkInfoPrinter extends DocumentVisitor {
            public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
                System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                        bookmarkStart.getBookmark().getText()));
                return VisitorAction.CONTINUE;
            }
        
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
                System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
                return VisitorAction.CONTINUE;
            }
        }
      • getFirstColumn

        public int getFirstColumn()
        
        Gets the zero-based index of the first column of the table column range associated with the bookmark. Returns -1 if this bookmark is not a table column bookmark.

        Example:

        Shows how to get information about table column bookmarks.
        Document doc = new Document(getMyDir() + "Table column bookmarks.doc");
        for (Bookmark bookmark : doc.getRange().getBookmarks()) {
            // If a bookmark encloses columns of a table, it is a table column bookmark, and its IsColumn flag set to true.
            System.out.println(MessageFormat.format("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()) {
                    // Print the contents of the first and last columns enclosed by the bookmark.
                    System.out.println(row.getCells().get(bookmark.getFirstColumn()).getText().trim());
                    System.out.println(row.getCells().get(bookmark.getLastColumn()).getText().trim());
                }
            }
        }
      • isColumn

        public boolean isColumn()
        
        Returns true if this bookmark is a table column bookmark.

        Example:

        Shows how to get information about table column bookmarks.
        Document doc = new Document(getMyDir() + "Table column bookmarks.doc");
        for (Bookmark bookmark : doc.getRange().getBookmarks()) {
            // If a bookmark encloses columns of a table, it is a table column bookmark, and its IsColumn flag set to true.
            System.out.println(MessageFormat.format("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()) {
                    // Print the contents of the first and last columns enclosed by the bookmark.
                    System.out.println(row.getCells().get(bookmark.getFirstColumn()).getText().trim());
                    System.out.println(row.getCells().get(bookmark.getLastColumn()).getText().trim());
                }
            }
        }
      • getLastColumn

        public int getLastColumn()
        
        Gets the zero-based index of the last column of the table column range associated with the bookmark. Returns -1 if this bookmark is not a table column bookmark.

        Example:

        Shows how to get information about table column bookmarks.
        Document doc = new Document(getMyDir() + "Table column bookmarks.doc");
        for (Bookmark bookmark : doc.getRange().getBookmarks()) {
            // If a bookmark encloses columns of a table, it is a table column bookmark, and its IsColumn flag set to true.
            System.out.println(MessageFormat.format("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()) {
                    // Print the contents of the first and last columns enclosed by the bookmark.
                    System.out.println(row.getCells().get(bookmark.getFirstColumn()).getText().trim());
                    System.out.println(row.getCells().get(bookmark.getLastColumn()).getText().trim());
                }
            }
        }
      • getName/setName

        public java.lang.String getName() / public void setName(java.lang.String value)
        
        Gets or sets the name of the bookmark. Note that if you change the name of a bookmark to a name that already exists in the document, no error will be given and only the first bookmark will be stored when you save the document.

        Example:

        Shows how to insert a bookmark.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // A valid bookmark has a name, a BookmarkStart, and a BookmarkEnd node.
        // Any whitespace in the names of bookmarks will be converted to underscores if we open the saved document with Microsoft Word. 
        // If we highlight the bookmark's name in Microsoft Word via Insert -> Links -> Bookmark, and press "Go To",
        // the cursor will jump to the text enclosed between the BookmarkStart and BookmarkEnd nodes.
        builder.startBookmark("My Bookmark");
        builder.write("Contents of MyBookmark.");
        builder.endBookmark("My Bookmark");
        
        // Bookmarks are stored in this collection.
        Assert.assertEquals("My Bookmark", doc.getRange().getBookmarks().get(0).getName());
        
        doc.save(getArtifactsDir() + "Bookmarks.Insert.docx");

        Example:

        Shows how to add bookmarks and update their contents.
        public void createUpdateAndPrintBookmarks() throws Exception
        {
            // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
            Document doc = createDocumentWithBookmarks(3);
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            printAllBookmarkInfo(bookmarks);
        
            // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
            bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
            bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");
        
            // Print all bookmarks again to see updated values.
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with a given number of bookmarks.
        /// </summary>
        private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            for (int i = 1; i <= numberOfBookmarks; i++)
            {
                String bookmarkName = "MyBookmark_" + i;
        
                builder.write("Text before bookmark.");
                builder.startBookmark(bookmarkName);
                builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
                builder.endBookmark(bookmarkName);
                builder.writeln("Text after bookmark.");
            }
        
            return doc;
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark in the collection.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception
        {
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get each bookmark in the collection to accept a visitor that will print its contents.
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                    if (currentBookmark != null)
                    {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Prints contents of every visited bookmark to the console.
        /// </summary>
        public static class BookmarkInfoPrinter extends DocumentVisitor {
            public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
                System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                        bookmarkStart.getBookmark().getText()));
                return VisitorAction.CONTINUE;
            }
        
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
                System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
                return VisitorAction.CONTINUE;
            }
        }
      • getText/setText

        public java.lang.String getText() / public void setText(java.lang.String value)
        
        Gets or sets the text enclosed in the bookmark.

        Example:

        Shows how to add bookmarks and update their contents.
        public void createUpdateAndPrintBookmarks() throws Exception
        {
            // Create a document with three bookmarks, then use a custom document visitor implementation to print their contents.
            Document doc = createDocumentWithBookmarks(3);
            BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
            printAllBookmarkInfo(bookmarks);
        
            // Bookmarks can be accessed in the bookmark collection by index or name, and their names can be updated.
            bookmarks.get(0).setName("{bookmarks[0].Name}_NewName");
            bookmarks.get("MyBookmark_2").setText("Updated text contents of {bookmarks[1].Name}");
        
            // Print all bookmarks again to see updated values.
            printAllBookmarkInfo(bookmarks);
        }
        
        /// <summary>
        /// Create a document with a given number of bookmarks.
        /// </summary>
        private static Document createDocumentWithBookmarks(int numberOfBookmarks) throws Exception
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
        
            for (int i = 1; i <= numberOfBookmarks; i++)
            {
                String bookmarkName = "MyBookmark_" + i;
        
                builder.write("Text before bookmark.");
                builder.startBookmark(bookmarkName);
                builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
                builder.endBookmark(bookmarkName);
                builder.writeln("Text after bookmark.");
            }
        
            return doc;
        }
        
        /// <summary>
        /// Use an iterator and a visitor to print info of every bookmark in the collection.
        /// </summary>
        private static void printAllBookmarkInfo(BookmarkCollection bookmarks) throws Exception
        {
            BookmarkInfoPrinter bookmarkVisitor = new BookmarkInfoPrinter();
        
            // Get each bookmark in the collection to accept a visitor that will print its contents.
            Iterator<Bookmark> enumerator = bookmarks.iterator();
        
            while (enumerator.hasNext()) {
                Bookmark currentBookmark = enumerator.next();
        
                    if (currentBookmark != null)
                    {
                    currentBookmark.getBookmarkStart().accept(bookmarkVisitor);
                    currentBookmark.getBookmarkEnd().accept(bookmarkVisitor);
        
                    System.out.println(currentBookmark.getBookmarkStart().getText());
                }
            }
        }
        
        /// <summary>
        /// Prints contents of every visited bookmark to the console.
        /// </summary>
        public static class BookmarkInfoPrinter extends DocumentVisitor {
            public int visitBookmarkStart(BookmarkStart bookmarkStart) throws Exception {
                System.out.println(MessageFormat.format("BookmarkStart name: \"{0}\", Content: \"{1}\"", bookmarkStart.getName(),
                        bookmarkStart.getBookmark().getText()));
                return VisitorAction.CONTINUE;
            }
        
            public int visitBookmarkEnd(BookmarkEnd bookmarkEnd) {
                System.out.println(MessageFormat.format("BookmarkEnd name: \"{0}\"", bookmarkEnd.getName()));
                return VisitorAction.CONTINUE;
            }
        }
    • Method Detail

      • remove

        public void remove()
                   throws java.lang.Exception
        Removes the bookmark from the document. Does not remove text inside the bookmark.

        Example:

        Shows how to remove bookmarks from a document.
        Document doc = new Document();
        DocumentBuilder builder = new DocumentBuilder(doc);
        
        // Insert five bookmarks with text inside their boundaries.
        for (int i = 1; i <= 5; i++) {
            String bookmarkName = "MyBookmark_" + i;
        
            builder.startBookmark(bookmarkName);
            builder.write(MessageFormat.format("Text inside {0}.", bookmarkName));
            builder.endBookmark(bookmarkName);
            builder.insertBreak(BreakType.PARAGRAPH_BREAK);
        }
        
        // This collection stores bookmarks.
        BookmarkCollection bookmarks = doc.getRange().getBookmarks();
        
        Assert.assertEquals(5, bookmarks.getCount());
        
        // There are several ways of removing bookmarks.
        // 1 -  Calling the bookmark's Remove method:
        bookmarks.get("MyBookmark_1").remove();
        
        Assert.assertFalse(IterableUtils.matchesAny(bookmarks, b -> b.getName() == "MyBookmark_1"));
        
        // 2 -  Passing the bookmark to the collection's Remove method:
        Bookmark bookmark = doc.getRange().getBookmarks().get(0);
        doc.getRange().getBookmarks().remove(bookmark);
        
        Assert.assertFalse(IterableUtils.matchesAny(bookmarks, b -> b.getName() == "MyBookmark_2"));
        
        // 3 -  Removing a bookmark from the collection by name:
        doc.getRange().getBookmarks().remove("MyBookmark_3");
        
        Assert.assertFalse(IterableUtils.matchesAny(bookmarks, b -> b.getName() == "MyBookmark_3"));
        
        // 4 -  Removing a bookmark at an index in the bookmark collection:
        doc.getRange().getBookmarks().removeAt(0);
        
        Assert.assertFalse(IterableUtils.matchesAny(bookmarks, b -> b.getName() == "MyBookmark_4"));
        
        // We can clear the entire bookmark collection.
        bookmarks.clear();
        
        // The text that was inside the bookmarks is still present in the document.
        Assert.assertEquals("Text inside MyBookmark_1.\r" +
                "Text inside MyBookmark_2.\r" +
                "Text inside MyBookmark_3.\r" +
                "Text inside MyBookmark_4.\r" +
                "Text inside MyBookmark_5.", doc.getText().trim());