Bookmarks can mark text, pictures, and places in a document, allowing you to jump straight to the desired text, picture, or place without scrolling through several paragraphs or pages. In this article, you will learn how to programmatically add a bookmark in an existing Word document using Free Spire.Doc for Java.
Introduction of the above mentioned free library:
https://www.e-iceblue.com/Introduce/free-doc-for-java.html
Installation
Method 1: Download the free library and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.
Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Sample Code
The Paragraph.appendBookmarkStart(java.lang.String name) method and Paragraph.appendBookmarkEnd(java.lang.String name) method offered by Free Spire.Doc for Java allows you to insert a bookmark with specified name into the specified paragraphs. The complete sample code are as follows.
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
public class InsertBookmark {
public static void main(String[] args) {
//Create a Document instance
Document doc = new Document();
//Load a sample Word file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\Place.docx");
//Get the first section
Section section = doc.getSections().get(0);
//Insert a bookmark with specified name into the specified paragraphs
section.getParagraphs().get(3).appendBookmarkStart("AncientCrust");
section.getParagraphs().get(6).appendBookmarkEnd("AncientCrust");
//Save the document
doc.saveToFile("AddBookmark.docx", FileFormat.Docx_2013);
}
}