Modify Hyperlinks in Word in Java

This article demonstrates how to modify hyperlinks in Word including modifying hyperlink address and display text using Spire.Doc for Java.

Below is the sample Word document we used for demonstration:

Modify Hyperlinks in Word in Java

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.util.ArrayList;
import java.util.List;

public class ModifyHyperlink {
    public static void main(String[] args) {
        //Load Word document
        Document doc = new Document();
        doc.loadFromFile("Hyperlink.docx");

        List hyperlinks = new ArrayList();

        //Loop through the section in the document
        for (Section section : (Iterable<Section>) doc.getSections()
                ) {
            //Loop through the section in the document
            for (Paragraph para : (Iterable<Paragraph>) section.getParagraphs()
                    ) {
                for (DocumentObject obj:(Iterable<DocumentObject>) para.getChildObjects()
                     ) {
                    if (obj.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                        Field field = (Field) obj;
                        if (field.getType().equals(FieldType.Field_Hyperlink)) {
                            hyperlinks.add(field);
                        }
                    }
                }
            }
        }

        hyperlinks.get(0).setCode("HYPERLINK \"http://www.google.com\"");
        hyperlinks.get(0).setFieldText("www.google.com");

        doc.saveToFile("EditHyperlink.docx", FileFormat.Docx_2013);
    }
}

Output:

Modify Hyperlinks in Word in Java