How to Add and Remove Hyperlink Fields in a Word Document in Java

How to Add and Remove Hyperlink Fields in a Word Document in Java

Aspose.Words FOSS for Java inserts hyperlinks as Word fields with DocumentBuilder.insertHyperlink. This guide inserts a web link and a link to a bookmark, lists the fields of the document and removes one, 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: Insert the Hyperlinks

insertHyperlink(displayText, urlOrBookmark, isBookmark) inserts a HYPERLINK field. Pass false for a web address and true for the name of a bookmark.


Step 4: List the Fields

doc.getRange().getFields() returns the fields. The run found 2 fields with the codes HYPERLINK "https://github.com/aspose-words-foss/Aspose.Words-FOSS-for-Java" and HYPERLINK \l "Intro".

import com.aspose.words.*;

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Visit ");
builder.insertHyperlink("the repository", "https://github.com/aspose-words-foss/Aspose.Words-FOSS-for-Java", false);
builder.write(" or read the ");
builder.insertHyperlink("introduction", "Intro", true);
builder.write(".");

Range range = doc.getRange();
FieldCollection fields = range.getFields();
System.out.println("Fields: " + fields.getCount());
for (Field f : fields) {
    System.out.println(f.getFieldCode().trim());
}

// Remove the first field again; its display text goes with it.
fields.get(0).remove();
System.out.println("Fields left: " + range.getFields().getCount());

The program printed:

Fields: 2
HYPERLINK "https://github.com/aspose-words-foss/Aspose.Words-FOSS-for-Java"
HYPERLINK \l "Intro"
Fields left: 1

Step 5: Remove a Field

Field.remove() removes the field from the document. The example removed the first one and 1 field was left.

Common Issues and Fixes

A hyperlink to a bookmark goes nowhere. The bookmark with that name does not exist in the document; create it with startBookmark and endBookmark.

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

How do I see the field code?

Field.getFieldCode returns it.

Do PAGE fields give page numbers?

No. Their results stay empty because this edition does not do page layout.

See Also