Hyperlinks in Word documents can lead readers to a webpage, an external file, an email address, and a specific place of the document being read. They are commonly used in Word documents for their convenience. This article will teach you how to use Spire.Doc for Java to find and extract hyperlinks in Word documents, including hypertexts and links.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.3.1</version>
    </dependency>
</dependencies>
    

Find and Extract a Specified Hyperlink in a Word Document

The detailed steps are as follows:

  • Create a Document instance and load a Word document from disk using Document.loadFromFile() method.
  • Create an object of ArrayList<Field>.
  • Iterate through the items in the sections to find all hyperlinks.
  • Get the text of the first hyperlink using Field.get().getFieldText() method and get its link using Field.get().getValue() method.
  • Save the text and the link of the first hyperlink to a TXT file using custom method writeStringToText().
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.io.*;
import java.util.ArrayList;

public class findHyperlinks {
    public static void main(String[] args) throws IOException {
        //Create a Document instance and load a Word document from file
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Create an object of ArrayList
        ArrayList hyperlinks = new ArrayList();

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable) doc.getSections()) {
            for (DocumentObject object : (Iterable) section.getBody().getChildObjects()) {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph)) {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable) paragraph.getChildObjects()) {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink)) {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }

        //Get the text and the address of the first hyperlink
        String hyperlinksText = hyperlinks.get(0).getFieldText();
        String hyperlinkAddress = hyperlinks.get(0).getValue();

        //Save the text and the link of the first hyperlink to a TXT file
        String output = "D:/javaOutput/HyperlinkTextAndLink.txt";
        writeStringToText("Text:\r\n" + hyperlinksText+ "\r\n" + "Link:\r\n" + hyperlinkAddress, output);
    }

    //Create a method to write the text and link of hyperlinks to a TXT file
    public static void writeStringToText(String content, String textFileName) throws IOException {
        File file = new File(textFileName);
        if (file.exists())
        {
            file.delete();
        }
        FileWriter fWriter = new FileWriter(textFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Java: Find and Extract Hyperlinks in Word Documents

Find and Extract All the Hyperlinks in a Word Document

The detailed steps are as follows:

  • Create a Document instance and load a Word document from disk using Document.loadFromFile() method.
  • Create an object of ArrayList<Field>.
  • Iterate through the items in the sections to find all hyperlinks.
  • Get the texts of the hyperlinks using Field.get().getFieldText() method and get their links using Field.get().getValue() method.
  • Save the text and the links of the hyperlinks to a TXT file using custom method writeStringToText().
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.io.*;
import java.util.ArrayList;

public class findHyperlinks {
    public static void main(String[] args) throws IOException {
        //Create a Document instance and load a Word document from file
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Create an object of ArrayList
        ArrayList hyperlinks = new ArrayList();
        String hyperlinkText = "";
        String hyperlinkAddress = "";

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable) doc.getSections()) {
            for (DocumentObject object : (Iterable) section.getBody().getChildObjects()) {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph)) {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable) paragraph.getChildObjects()) {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink)) {
                                hyperlinks.add(field);

                                //Get the texts and links of all hyperlinks
                                hyperlinkText += field.getFieldText() + "\r\n";
                                hyperlinkAddress += field.getValue() + "\r\n";
                            }
                        }
                    }
                }
            }
        }

        //Save the texts and the links of the hyperlinks to a TXT file
        String output = "D:/javaOutput/HyperlinksTextsAndLinks.txt";
        writeStringToText("Text:\r\n " + hyperlinkText + "\r\n" + "Link:\r\n" + hyperlinkAddress + "\r\n", output);
    }

    //Create a method to write the text and link of hyperlinks to a TXT file
    public static void writeStringToText(String content, String textFileName) throws IOException {
        File file = new File(textFileName);
        if (file.exists())
        {
            file.delete();
        }
        FileWriter fWriter = new FileWriter(textFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Java: Find and Extract Hyperlinks in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Hyperlink

Hyperlinks usually appear on texts. By clicking on a hyperlink, we can access a website, a document, an email address, or other elements. Some Word documents, especially those that are generated from web content, may contain irritating hyperlinks, such as advertisements. This article shows you how to programmatically remove one hyperlink or all hyperlinks in a Word document using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.3.1</version>
    </dependency>
</dependencies>
    

Remove a Specified Hyperlink in a Word Document

The detailed steps to remove a specified hyperlink in a Word file are as follows:

  • Create a Document object and load a Word document from disk using Document.loadFromFile() method.
  • Find all the hyperlinks using custom method FindAllHyperlinks().
  • Flatten the first hyperlink using custom method FlattenHyperlinks().
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.TextRange;

import java.awt.*;
import java.util.ArrayList;

public class removeHyperlink {
    public static void main(String[] args) {
        //Create a Document object and load a Word document from disk
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Find all hyperlinks
        ArrayList hyperlinks = FindAllHyperlinks(doc);

        //Flatten the first hyperlink
        FlattenHyperlinks(hyperlinks.get(0));

        //Save the document to file
        String output = "D:/javaOutput/RemoveHyperlinks.docx";
        doc.saveToFile(output, FileFormat.Docx);
    }

    //Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
    private static ArrayList FindAllHyperlinks(Document document)
    {
        ArrayList hyperlinks = new ArrayList();

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable)document.getSections())
        {
            for (DocumentObject object : (Iterable)section.getBody().getChildObjects())
            {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph))
                {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable)paragraph.getChildObjects())
                    {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field))
                        {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink))
                            {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }
        return hyperlinks;
    }

    //Create a method FlattenHyperlinks() to flatten the hyperlink field
    public static void FlattenHyperlinks(Field field)
    {
        int ownerParaIndex = field.getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getOwnerParagraph());
        int fieldIndex = field.getOwnerParagraph().getChildObjects().indexOf(field);
        Paragraph sepOwnerPara = field.getSeparator().getOwnerParagraph();
        int sepOwnerParaIndex = field.getSeparator().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getSeparator().getOwnerParagraph());
        int sepIndex = field.getSeparator().getOwnerParagraph().getChildObjects().indexOf(field.getSeparator());
        int endIndex = field.getEnd().getOwnerParagraph().getChildObjects().indexOf(field.getEnd());
        int endOwnerParaIndex = field.getEnd().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getEnd().getOwnerParagraph());
        FormatFieldResultText(field.getSeparator().getOwnerParagraph().ownerTextBody(), sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);
        field.getEnd().getOwnerParagraph().getChildObjects().removeAt(endIndex);
        for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
        {
            if (i == sepOwnerParaIndex && i == ownerParaIndex)
            {
                for (int j = sepIndex; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }
            }
            else if (i == ownerParaIndex)
            {
                for (int j = field.getOwnerParagraph().getChildObjects().getCount() - 1; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }
            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex; j >= 0; j--)
                {
                    sepOwnerPara.getChildObjects().removeAt(j);
                }
            }
            else
            {
                field.getOwnerParagraph().ownerTextBody().getChildObjects().removeAt(i);
            }
        }
    }

    //Create a method FormatFieldResultText() to remove the font color and underline format of the hyperlinks
    private static void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
    {
        for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
        {
            Paragraph para = (Paragraph) ownerBody.getChildObjects().get(i);
            if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < endIndex; j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < para.getChildObjects().getCount(); j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == endOwnerParaIndex)
            {
                for (int j = 0; j < endIndex; j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else
            {
                for (int j = 0; j < para.getChildObjects().getCount(); j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
        }
    }

    //Create a method FormatText() to change the color of the text to black and remove the underline
    private static void FormatText(TextRange tr)
    {
        //Set the text color to black
        tr.getCharacterFormat().setTextColor(Color.black);

        //Set the text underline style to none
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None);
    }
}

Java: Remove Hyperlinks in Word Documents

Remove All the Hyperlinks in a Word Document

The detailed steps to remove all the hyperlinks in a Word file are as follows:

  • Create a Document object and load a Word document from disk using Document.loadFromFile() method.
  • Find all the hyperlinks using custom method FindAllHyperlinks().
  • Loop through the hyperlinks, and invoke the custom method FlattenHyperlinks() to flatten the specific hyperlink.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.UnderlineStyle;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.TextRange;

import java.awt.*;
import java.util.ArrayList;

public class removeHyperlink {
    public static void main(String[] args) {
        //Create a Document object and load a Word document from disk
        String input = "D:/testp/test.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //Find all the hyperlinks
        ArrayList hyperlinks = FindAllHyperlinks(doc);

        //Loop through the hyperlinks, and flatten the specific hyperlink.
        for (int i = hyperlinks.size() -1; i >= 0; i--)
        {
            FlattenHyperlinks(hyperlinks.get(i));
        }

        //Save the document to file
        String output = "D:/javaOutput/RemoveHyperlinks.docx";
        doc.saveToFile(output, FileFormat.Docx);
    }

    //Create a method FindAllHyperlinks() to get all the hyperlinks from the sample document
    private static ArrayList FindAllHyperlinks(Document document)
    {
        ArrayList hyperlinks = new ArrayList();

        //Iterate through the items in the sections to find all hyperlinks
        for (Section section : (Iterable)document.getSections())
        {
            for (DocumentObject object : (Iterable)section.getBody().getChildObjects())
            {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph))
                {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable)paragraph.getChildObjects())
                    {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field))
                        {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink))
                            {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }
        return hyperlinks;
    }

    //Create a method FlattenHyperlinks() to flatten the hyperlink field
    public static void FlattenHyperlinks(Field field)
    {
        int ownerParaIndex = field.getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getOwnerParagraph());
        int fieldIndex = field.getOwnerParagraph().getChildObjects().indexOf(field);
        Paragraph sepOwnerPara = field.getSeparator().getOwnerParagraph();
        int sepOwnerParaIndex = field.getSeparator().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getSeparator().getOwnerParagraph());
        int sepIndex = field.getSeparator().getOwnerParagraph().getChildObjects().indexOf(field.getSeparator());
        int endIndex = field.getEnd().getOwnerParagraph().getChildObjects().indexOf(field.getEnd());
        int endOwnerParaIndex = field.getEnd().getOwnerParagraph().ownerTextBody().getChildObjects().indexOf(field.getEnd().getOwnerParagraph());
        FormatFieldResultText(field.getSeparator().getOwnerParagraph().ownerTextBody(), sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);
        field.getEnd().getOwnerParagraph().getChildObjects().removeAt(endIndex);
        for (int i = sepOwnerParaIndex; i >= ownerParaIndex; i--)
        {
            if (i == sepOwnerParaIndex && i == ownerParaIndex)
            {
                for (int j = sepIndex; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }
            }
            else if (i == ownerParaIndex)
            {
                for (int j = field.getOwnerParagraph().getChildObjects().getCount() - 1; j >= fieldIndex; j--)
                {
                    field.getOwnerParagraph().getChildObjects().removeAt(j);
                }
            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex; j >= 0; j--)
                {
                    sepOwnerPara.getChildObjects().removeAt(j);
                }
            }
            else
            {
                field.getOwnerParagraph().ownerTextBody().getChildObjects().removeAt(i);
            }
        }
    }

    //Create a method FormatFieldResultText() to format the texts
    private static void FormatFieldResultText(Body ownerBody, int sepOwnerParaIndex, int endOwnerParaIndex, int sepIndex, int endIndex)
    {
        for (int i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++)
        {
            Paragraph para = (Paragraph) ownerBody.getChildObjects().get(i);
            if (i == sepOwnerParaIndex && i == endOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < endIndex; j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == sepOwnerParaIndex)
            {
                for (int j = sepIndex + 1; j < para.getChildObjects().getCount(); j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else if (i == endOwnerParaIndex)
            {
                for (int j = 0; j < endIndex; j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
            else
            {
                for (int j = 0; j < para.getChildObjects().getCount(); j++)
                {
                    FormatText((TextRange)para.getChildObjects().get(j));
                }
            }
        }
    }

    //Create a method FormatText() to change the color of the text to black and remove the underline
    private static void FormatText(TextRange tr)
    {
        //Set the text color to black
        tr.getCharacterFormat().setTextColor(Color.black);

        //Set the text underline style to none
        tr.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None);
    }
}

Java: Remove Hyperlinks in Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Hyperlink

Hyperlinks in Word documents are usually displayed blue with an underline. Actually, if you don't like the default style of hyperlinks, you can change the color of hyperlinks or remove the underline to make your own hyperlink style while keeping the link. This article shows how to change the color or remove the underline of hyperlinks in Word by programming using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.3.1</version>
    </dependency>
</dependencies>
    

Change the Color of a Hyperlink or Remove the Underline of a Hyperlink in a Word Document

The detailed steps are as follows:

  • Create an object of Document class.
  • Add a section to the document using Document.addSection() method.
  • Add a paragraph to the section using Section.addParagraph() method.
  • Insert a normal hyperlink using Paragraph.appendHyperlink() method.
  • Add a paragraph and a hyperlink, and then change the color of the hyperlink text to red using TextRange.getCharacterFormat().setTextColor() method.
  • Add a paragraph and a hyperlink, and then remove the underline of the hyperlink using TextRange.getCharacterFormat().setUnderlineStyle() method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextRange;

import java.awt.*;

public class ChangeHyperlink {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Add a section
        Section section = document.addSection();

        //Add a paragraph
        Paragraph para= section.addParagraph();
        para.appendText("A regular hyperlink: ");

        //Insert a hyperlink
        TextRange textRange = para.appendHyperlink("www.e-iceblue.com", "E-iceblue", HyperlinkType.Web_Link);
        textRange.getCharacterFormat().setFontName("Times New Roman");
        textRange.getCharacterFormat().setFontSize(12f);
        para.appendBreak(BreakType.Line_Break);


        //Add a paragraph
        para = section.addParagraph();
        para.appendText("Change the color of the hyperlink: ");

        //Insert a hyperlink
        textRange = para.appendHyperlink("www.e-iceblue.com", "E-iceblue", HyperlinkType.Web_Link);
        textRange.getCharacterFormat().setFontName("Times New Roman");
        textRange.getCharacterFormat().setFontSize(12f);
        //Change the color of the hyperlink to red
        textRange.getCharacterFormat().setTextColor(Color.RED);
        para.appendBreak(BreakType.Line_Break);

        //Add a paragraph
        para = section.addParagraph();
        para.appendText("Remove the underline of the hyperlink: ");

        //Insert a hyperlink
        textRange = para.appendHyperlink("www.e-iceblue.com", "E-iceblue", HyperlinkType.Web_Link);
        textRange.getCharacterFormat().setFontName("Times New Roman");
        textRange.getCharacterFormat().setFontSize(12f);
        //Remove the underline of the hyperlink
        textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.None);

        //Save the document
        document.saveToFile("ChangeHyperlink.docx", FileFormat.Docx_2013);
    }
}

Java: Change the Color or Remove the Underline of Hyperlinks in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Hyperlink
Tuesday, 12 November 2019 05:56

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

Published in Hyperlink
Friday, 05 August 2022 09:36

Java: Add Hyperlinks to Word Documents

A hyperlink is the most important element that we use in digital documents to make connections between two things. When readers click on a hyperlink in a Word document, it will take them to a different location within the document, to a different file or website, or to a new email message. This article introduces how to add hyperlinks to Word documents in Java using Spire.Doc for Java.

Install Spire.Doc for Java

First, you're required to add the Spire.Doc.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>12.3.1</version>
    </dependency>
</dependencies>
    

Insert Hyperlinks When Adding Paragraphs to Word

Spire.Doc for Java offers the Paragraph.appendHyperlink() method to add a web link, an email link, a file link, or a bookmark link to a piece of text or an image inside a paragraph. The following are the detailed steps.

  • Create a Document object.
  • Add a section and a paragraph to it.
  • Insert a hyperlink based on text using Paragraph.appendHyerplink(String link, String text, HyperlinkType type) method.
  • Add an image to the paragraph using Paragraph.appendPicture() method.
  • Add a hyperlink to the image using Paragraph.appendHyerplink(String link, DocPicture picture, HyperlinkType type) method.
  • Save the document using Document.saveToFile() method.
  • Java
import com.spire.doc.BookmarkStart;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.HyperlinkType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.DocPicture;

public class InsertHyperlinks {

    public static void main(String[] args) {

        //Create a Word document
        Document doc = new Document();

        //Add a section
        Section section = doc.addSection();

        //Add a paragraph
        Paragraph paragraph = section.addParagraph();
        paragraph.appendHyperlink("https://www-iceblue.com/", "Home Page", HyperlinkType.Web_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add an email link
        paragraph.appendHyperlink("mailto:support@e-iceblue.com", "Mail Us", HyperlinkType.E_Mail_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add a file link
        String filePath = "C:\\Users\\Administrator\\Desktop\\report.xlsx";
        paragraph.appendHyperlink(filePath, "Click to open the report", HyperlinkType.File_Link);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add another section and create a bookmark
        Section section2 = doc.addSection();
        Paragraph bookmarkParagraph = section2.addParagraph();
        bookmarkParagraph.appendText("Here is a bookmark");
        BookmarkStart start = bookmarkParagraph.appendBookmarkStart("myBookmark");
        bookmarkParagraph.getItems().insert(0, start);
        bookmarkParagraph.appendBookmarkEnd("myBookmark");

        //Link to the bookmark
        paragraph.appendHyperlink("myBookmark", "Jump to a location inside this document", HyperlinkType.Bookmark);

        //Append line breaks
        paragraph.appendBreak(BreakType.Line_Break);
        paragraph.appendBreak(BreakType.Line_Break);

        //Add an image link
        String imagePath = "C:\\Users\\Administrator\\Desktop\\logo.png";
        DocPicture picture = paragraph.appendPicture(imagePath);
        paragraph.appendHyperlink("https://www.e-iceblue.com/", picture, HyperlinkType.Web_Link);

        //Save to file
        doc.saveToFile("output/InsertHyperlinks.docx", FileFormat.Docx_2013);
    }
}

Java: Add Hyperlinks to Word Documents

Add Hyperlinks to Existing Text in Word

Adding hyperlinks to existing text in a document is a bit more complicated. You need to find the target string first, and then replace it in the paragraph with a hyperlink field. The following are the steps.

  • Create a Document object.
  • Load a Word file using Document.loadFromFile() method.
  • Find all the occurrences of the target string in the document using Document.findAllString() method, and get the specific one by its index from the collection.
  • Get the string’s own paragraph and its position in it.
  • Remove the string from the paragraph.
  • Create a hyperlink field and insert it to position where the string is located.
  • Save the document to another file using Document.saveToFle() method.
  • Java
import com.spire.doc.Document;
import com.spire.doc.FieldType;
import com.spire.doc.FileFormat;
import com.spire.doc.Hyperlink;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;
import com.spire.doc.fields.FieldMark;
import com.spire.doc.fields.TextRange;
import com.spire.doc.interfaces.IParagraphBase;
import com.spire.doc.interfaces.ITextRange;

import java.awt.*;

public class AddHyperlinksToExistingText {

    public static void main(String[] args) {

        //Create a Document object
        Document document = new Document();

        //Load a Word file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");

        //Find all the occurrences of the string "Java" in the document
        TextSelection[] selections = document.findAllString("Java", true, true);

        //Get the second occurrence
        TextRange range = selections[1].getAsOneRange();

        //Get its owner paragraph
        Paragraph paragraph = range.getOwnerParagraph();

        //Get its position in the paragraph
        int index = paragraph.getItems().indexOf(range);

        //Remove it from the paragraph
        paragraph.getItems().remove(range);

        //Create a hyperlink field
        Field field = new Field(document);
        field.setType(FieldType.Field_Hyperlink);
        Hyperlink hyperlink = new Hyperlink(field);
        hyperlink.setType(HyperlinkType.Web_Link);
        hyperlink.setUri("https:\\en.wikipedia.org\\wiki\\Java_(programming_language)");
        paragraph.getItems().insert(index, field);

        //Insert a field mark "start" to the paragraph
        IParagraphBase item = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark start = (FieldMark)item;
        start.setType(FieldMarkType.Field_Separator);
        paragraph.getItems().insert(index + 1, start);

        //Insert a text range between two field marks
        ITextRange textRange = new TextRange(document);
        textRange.setText("Java");
        textRange.getCharacterFormat().setFontName(range.getCharacterFormat().getFontName());
        textRange.getCharacterFormat().setFontSize(range.getCharacterFormat().getFontSize());
        textRange.getCharacterFormat().setBold(range.getCharacterFormat().getBold());
        textRange.getCharacterFormat().setTextColor(Color.blue);
        textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);
        paragraph.getItems().insert(index + 2, textRange);

        //Insert a field mark "end" to the paragraph
        IParagraphBase item2 = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark end = (FieldMark)item2;
        end.setType(FieldMarkType.Field_End);
        paragraph.getItems().insert(index + 3, end);

        //Save to file
        document.saveToFile("output/AddHyperlink.docx", FileFormat.Docx_2013);
    }
}

Java: Add Hyperlinks to Word Documents

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Published in Hyperlink