How to Fill a Bookmark in a Word Document in Java
Aspose.Words FOSS for Java names a position in a Word document with a bookmark. This guide fills a bookmark named Customer with new text, saves the document and removes the bookmark, with the library from Maven Central.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Mark the Text
Write the text with a DocumentBuilder and wrap the part to fill between startBookmark and endBookmark, both given the name Customer.
Step 4: Replace the Text and Save
Look the bookmark up with doc.getRange().getBookmarks().get("Customer"), call setText and save. Reloading the file and reading its text printed the new text.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Dear ");
builder.startBookmark("Customer");
builder.write("customer name");
builder.endBookmark("Customer");
builder.write(", welcome.");
// Replace the text inside the bookmark, then save and reload the document.
doc.getRange().getBookmarks().get("Customer").setText("Acme Corp");
doc.save("welcome.docx");
Document reloaded = new Document("welcome.docx");
System.out.println(reloaded.getText().trim());
// Remove the bookmark; its text stays in the document.
reloaded.getRange().getBookmarks().remove("Customer");
System.out.println("Bookmarks left: " + reloaded.getRange().getBookmarks().getCount());
System.out.println(reloaded.getText().trim());The program printed:
Dear Acme Corp, welcome.
Bookmarks left: 0
Dear Acme Corp, welcome.Step 5: Remove the Bookmark
getBookmarks().remove takes the bookmark name. The example printed 0 bookmarks left, and the text was still in the document.
Common Issues and Fixes
The bookmark is not found. The name does not match any bookmark in the range, and get then returns null. Check that startBookmark and endBookmark used the same name and test the result for null before you call setText.
The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.
Frequently Asked Questions
Does remove delete the text?
No. The text stayed in the document in the example.
How do I count bookmarks?
BookmarkCollection.getCount returns the number of bookmarks in the collection.