Insert and Remove Bookmarks in Word in Java

This article demonstrates how to add and delete bookmarks in an existing Word document using Spire.Doc for Java.

Insert Bookmark

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class InsertBookmark {

    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\\sample.docx");

        //get the the paragraph where you want to insert bookmark
        Paragraph paragraph = doc.getSections().get(0).getParagraphs().get(1);

        //append a bookmark start and remove it to the beginning of the paragraph
        BookmarkStart start = paragraph.appendBookmarkStart("myBookmark");
        paragraph.getItems().insert(0,start);
        
        //append a bookmark end at the end of the paragraph
        paragraph.appendBookmarkEnd("myBookmark");
        
        //save the file
        doc.saveToFile("output/AddBookmark.docx", FileFormat.Docx_2013);
    }
}

Insert and Remove Bookmarks in Word in Java

Remove Bookmark

import com.spire.doc.Bookmark;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class RemoveBookmark {

    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\\AddBookmark.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);
    }
}

Insert and Remove Bookmarks in Word in Java