Java – How to Add or Remove Bookmarks in a Word Document
Tags: java, msword, bookmark, library
Published: 2022-03-14 07:19:15

In Microsoft Word, you can bookmark a phrase, paragraph, object, etc. Adding a bookmark to a place gives you a shortcut to find information you'll want to reference later. If you no longer need a bookmark, you can delete it at any time.

In this article, I am going to introduce how to **add or remove bookmarks in a Word document** using [Free Spire.Doc for Java](https://www.e-iceblue.com/Introduce/free-doc-for-java.html), which is a free Java library for creating and manipulating MS Word documents. 

- <a href="#example-1-add-a-bookmark-to-a-specific-paragraph">Add a bookmark to a specific paragraph</a>
- [Add a bookmark to a selected range of text](#example-2-add-a-bookmark-to-a-selected-range-of-text)
- [Remove a bookmark by its index](#example-3-remove-a-bookmark-by-its-index)

##Add Spire.Doc.jar as dependency
If you are working on a maven project, you can include the dependency in pom.xml file using this:
```java
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>5.2.0</version>
    </dependency>
</dependencies>
```
If you are not using maven, then you can find the required jar files from the zip file available in [this location](https://www.e-iceblue.com/Download/doc-for-java-free.html). Include all the jar files into the application lib folder to run the sample code given in this tutorial.
##Example 1. Add a bookmark to a specific paragraph
Free Spire.Doc for Java offers a **BookmarkStart** class and a **BookmarkEnd** class to represent the start mark and the end mark, respectively. To add a bookmark to a whole paragraph, position the start mark at the beginning of the paragraph and the end mark at the end. The detailed steps are as follows.

- Create a **Document** object.
- Load a Word file using **Document.LoadFromFile()** method.
- Get a section from the document using **Document.getSections().get()** method.
- Get a specific paragraph from the section using **Section.getParagraphs().get()** method.
- Create a BookmarkStart object, and insert it at the beginning of the paragraph using **Paragraph.getItems().insert()** method.
- Create a **BookmarkEnd** object, and insert it at the end of the paragraph using **Paragraph.appendBookmarkEnd()** method.
- Save the document to anther file using **Document.saveToFile()** method.

The following is the code snippet of adding a bookmark to a specific paragraph using [Free Spire.Doc for Java](https://www.e-iceblue.com/Introduce/free-doc-for-java.html) library. 
```java
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class AddBookmarkToParagraph {

    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();

        //Load a sample Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //Get the third paragraph （paragraph index starts at 0）
        Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(2);

        //Create a bookmark start
        BookmarkStart start = paragraph.appendBookmarkStart("myBookmark");

        //Insert it at the beginning of the paragraph
        paragraph.getItems().insert(0,start);

        //Append a bookmark end at the end of the paragraph
        paragraph.appendBookmarkEnd("myBookmark");

        //save the file
        doc.saveToFile("output/AddBookmarkToParagraph.docx", FileFormat.Docx_2013);
    }
}
```

![BookmarkParagraph](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pafryjgx99olajdnk3sw.png)
##Example 2. Add a bookmark to a selected range of text
To add a bookmark to a selected range of text, we need first find the text range from the document. And then get its index in its owner paragraph. The index will determine where to insert the start mark and end mark. Here are the detailed steps.

- Create a **Document** object.
- Load a Word file using **Document.LoadFromFile()** method.
- Find all occurrences of a certain string using **Document.findAllString()** method, and then get the specific occurrence from the collection.
- Get the owner paragraph of the string using **TextSelection.getAsOneEange().getOwnerParagraph()** method.
- Get the index of the string in the paragraph using **Paragraph.getChildObjects().indexOf()** method.
- Create a **BookmarkStart** object and a **BookmarkEnd** object, and insert them to the paragraph at the specified index position.
- Save the document to anther file using **Document.saveToFile()** method.
The following is the code snippet to add a bookmark to a selected range of text using [Free Spire.Doc for Java](https://www.e-iceblue.com/Introduce/free-doc-for-java.html) library.
```java
import com.spire.doc.BookmarkEnd;
import com.spire.doc.BookmarkStart;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.TextSelection;

public class AddBookmarkToSelectedRangeOfText {

    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();

        //Load a sample Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //String to find
        String stringToFind = "what background images or background colors are to be used";

        //Find the selected text from the document
        TextSelection[] finds = doc.findAllString(stringToFind, false, true);
        TextSelection specificText = finds[0];

        //Find the paragraph where the text is located
        Paragraph para = specificText.getAsOneRange().getOwnerParagraph();

        //Get the index of the text in the paragraph
        int index = para.getChildObjects().indexOf(specificText.getAsOneRange());

        //Create a bookmark start
        BookmarkStart start = para.appendBookmarkStart("myBookmark");

        //Insert the bookmark start at the index position
        para.getChildObjects().insert(index, start);

        //Create a bookmark end
        BookmarkEnd end = para.appendBookmarkEnd("myBookmark");

        //Insert the bookmark end at the end of the selected text
        para.getChildObjects().insert(index + 2, end);

        //Save the document to another file
        doc.saveToFile("output/AddBookmarkToSelectedText.docx", FileFormat.Docx_2013);
    }
}
```
![BookmarkPhrase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rysvg5r4epyhq62fkfdy.png)
##Example 3. Remove a bookmark by its index
Removing bookmarks is quite easy using this library. The following are the steps and the code example.

- Create a **Document** object.
- Load a Word file using **Document.LoadFromFile()** method.
- Get a collection of bookmarks from the document using **Document.getBookmarks()** method.
- Get a specific bookmark using **Bookmarks.get()** method.
- Remove the bookmark using **Bookmarks.remove()** method.
- Save the document to anther file using **Document.saveToFile()** method.
```java
import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class DeleteBookmark {

    public static void main(String[] args) {

        //Create a Document object
        Document doc = new Document();

        //Load an existing Word file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Bookmarks.docx");

        //Get bookmark by its index
        Bookmark bookmark = doc.getBookmarks().get(0);

        //Remove the bookmark
        doc.getBookmarks().remove(bookmark);

        //Save the document.
        doc.saveToFile("output/RemoveBookmark.docx", FileFormat.Docx);
    }
}
```

![RemoveBookmark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u1gtix51o5yj4pkl2o3m.png)