How to Add Hyperlinks to Word Documents in Java

java dev.to

Hyperlinks in Word documents are not limited to opening web pages. They can also link to email addresses, local files, bookmarks within the same document, and even images. In technical documents, project reports, user manuals, and multi-section documents, hyperlinks help readers navigate information more efficiently.

For a small document, adding hyperlinks manually in Microsoft Word may be acceptable. However, when you need to add links to multiple keywords, generate documents in batches, or process many files automatically, using Java is more efficient and helps keep hyperlink formatting consistent.

This article shows how to work with Word hyperlinks in Java, including how to add web links, email links, file links, bookmark links, image hyperlinks, and hyperlinks to existing text. It also includes a complete example for batch-adding reference links to keywords in a technical document.

Environment Setup

Before writing the code, you need a Java development environment and a library for working with Word documents. The examples in this article use Spire.Doc for Java, which can create, read, edit, and save Word documents without requiring Microsoft Word to be installed.

1. Add the Maven Dependency

If your project uses Maven, add the following configuration to your 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>14.6.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If you use Gradle, add the following configuration:

repositories {
    maven {
        url 'https://repo.e-iceblue.com/nexus/content/groups/public/'
    }
}

dependencies {
    implementation 'e-iceblue:spire.doc:14.6.0'
}
Enter fullscreen mode Exit fullscreen mode

2. Prepare Test Files

Some examples in this article create a new Word document directly. Other examples load an existing Word document by using the loadFromFile() method:

document.loadFromFile("sample.docx");
Enter fullscreen mode Exit fullscreen mode

This means the program reads sample.docx from the current project directory. If the file is stored elsewhere, use a full file path instead:

document.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.docx");
Enter fullscreen mode Exit fullscreen mode

Similarly, if the code uses external images or files, make sure those files exist and the paths are correct. Otherwise, the generated hyperlink may not open the target file, or the image may fail to be inserted into the document.

Add Web and Email Links to a Word Document

Web links and email links are the most common hyperlink types in Word documents. They are often used for official websites, online references, documentation pages, support pages, or contact information.

In Spire.Doc for Java, you can use the paragraph.appendHyperlink() method to add a hyperlink to a paragraph. You need to specify the target address, the display text, and the hyperlink type.

The following example adds a web link and an email link to a Word document:

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

public class WebAndEmailLinks {
    public static void main(String[] args) {
        // Create a Word document
        Document doc = new Document();
        Section section = doc.addSection();
        Paragraph paragraph = section.addParagraph();

        // Add a web link
        paragraph.appendHyperlink(
            "https://www.google.com/",
            "Visit Google",
            HyperlinkType.Web_Link
        );

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

        // Add an email link
        paragraph.appendHyperlink(
            "mailto:12345@mail.com",
            "Contact Us",
            HyperlinkType.E_Mail_Link
        );

        // Save the document
        doc.saveToFile("output/web_email_links.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Note that whether an email link opens correctly depends on whether the user has a default email client configured on their machine.

Link to an External File

In project documentation, financial reports, or resource lists, you may need to link from a Word document to an external file, such as an Excel workbook, a PDF document, an image, or another supporting file. This allows users to access related materials from a single Word index document.

For this type of hyperlink, use HyperlinkType.File_Link. The target path can be either a relative path or an absolute path. In real projects, relative paths are often preferred because they are less likely to break when the whole folder is moved together.

The following example creates a hyperlink to an external Excel file:

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

public class FileLink {
    public static void main(String[] args) {
        Document doc = new Document();
        Section section = doc.addSection();
        Paragraph paragraph = section.addParagraph();

        // Create a link to an external file
        String filePath = "C:\\Users\\Admin\\Desktop\\report.xlsx";
        paragraph.appendHyperlink(
            filePath,
            "View Report",
            HyperlinkType.File_Link
        );

        doc.saveToFile("output/file_link.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

When sharing the Word document with others, make sure the linked files are also available to the recipient. Otherwise, the file links may not work on another computer.

Link to a Bookmark Inside the Word Document

Internal links are useful in long or multi-section Word documents. They allow readers to jump from a table of contents page to a specific chapter, from an introduction to an appendix, or from a summary section to detailed data.

To create an internal hyperlink in Spire.Doc for Java, you need to create a bookmark first, and then add a hyperlink that points to that bookmark. The hyperlink type should be set to HyperlinkType.Bookmark.

The following example creates a bookmark and adds a link to it:

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

public class BookmarkLink {
    public static void main(String[] args) {
        Document doc = new Document();

        // First section: add a hyperlink to the bookmark
        Section section1 = doc.addSection();
        Paragraph linkPara = section1.addParagraph();
        linkPara.appendHyperlink(
            "myBookmark",
            "Go to Chapter 2",
            HyperlinkType.Bookmark
        );

        // Second section: create the bookmark target
        Section section2 = doc.addSection();
        Paragraph bookmarkPara = section2.addParagraph();

        // Add bookmark start, text, and bookmark end
        bookmarkPara.appendBookmarkStart("myBookmark");
        bookmarkPara.appendText("This is the content of Chapter 2.");
        bookmarkPara.appendBookmarkEnd("myBookmark");

        doc.saveToFile("output/bookmark_link.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Common use cases include:

  • Linking a contents page to chapters

  • Linking an introduction to detailed explanations

  • Linking a summary to raw data sections

  • Linking glossary terms to definitions

  • Creating quick navigation in long documents

Bookmark names should be short and clear. Avoid special characters where possible. For example:

"chapter1"      // Chapter 1
"appendix_a"    // Appendix A
"conclusion"    // Conclusion
Enter fullscreen mode Exit fullscreen mode

Keeping bookmark names simple helps reduce path or name resolution issues.

Add a Hyperlink to an Image in Word

Word hyperlinks can also be applied to images. This is useful when creating clickable logos, icon buttons, help entries, or navigation images.

In Spire.Doc for Java, you can insert an image by using paragraph.appendPicture(), and then call paragraph.appendHyperlink() to make the image clickable.

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

public class ImageHyperlink {
    public static void main(String[] args) {
        Document doc = new Document();
        Section section = doc.addSection();
        Paragraph paragraph = section.addParagraph();

        // Insert an image
        String imagePath = "C:\\Users\\Admin\\Desktop\\logo.png";
        DocPicture picture = paragraph.appendPicture(imagePath);

        // Add a hyperlink to the image
        paragraph.appendHyperlink(
            "https://www.e-iceblue.com/",
            picture,
            HyperlinkType.Web_Link
        );

        doc.saveToFile("output/image_link.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • paragraph.appendPicture(imagePath) inserts the image into the paragraph.

  • The second parameter of appendHyperlink() is the image object, which means the hyperlink is applied to the image.

  • The third parameter specifies that the hyperlink is a web link.

Make sure the image path is correct before running the code. If the image file cannot be found, it will not be inserted into the document.

Add a Hyperlink to Existing Text

In many real projects, the Word document already exists, and you need to add hyperlinks to specific text, such as keywords, product names, class names, or reference terms. In this case, you cannot simply use appendHyperlink() because that method is mainly used to append new hyperlink content.

To convert existing text into a hyperlink, you need to build a Word hyperlink field structure.

A Word hyperlink field usually contains the following parts:

  1. Field - the field start object

  2. Field_Separator - the separator between the field code and display text

  3. TextRange - the visible hyperlink text

  4. Field_End - the field end marker

The following example adds a hyperlink to the first occurrence of the word Java in an existing Word document:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.interfaces.*;
import java.awt.Color;

public class AddLinkToExistingText {
    public static void main(String[] args) {
        // Load an existing Word document
        Document document = new Document();
        document.loadFromFile("input/sample.docx");

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

        if (selections.length > 0) {
            // Get the first matched text range
            TextRange range = selections[0].getAsOneRange();

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

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

            // Remove the original text range
            paragraph.getItems().remove(range);

            // 1. 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);

            // 2. Insert the field separator
            IParagraphBase separator = document.createParagraphItem(ParagraphItemType.Field_Mark);
            FieldMark start = (FieldMark) separator;
            start.setType(FieldMarkType.Field_Separator);
            paragraph.getItems().insert(index + 1, start);

            // 3. Insert the display text and preserve part of the original formatting
            ITextRange textRange = new TextRange(document);
            textRange.setText("Java");

            textRange.getCharacterFormat().setFontName(
                range.getCharacterFormat().getFontName()
            );
            textRange.getCharacterFormat().setFontSize(
                range.getCharacterFormat().getFontSize()
            );

            // Apply a common hyperlink style: blue text with underline
            textRange.getCharacterFormat().setTextColor(Color.blue);
            textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);

            paragraph.getItems().insert(index + 2, textRange);

            // 4. Insert the field end marker
            IParagraphBase endItem = document.createParagraphItem(ParagraphItemType.Field_Mark);
            FieldMark end = (FieldMark) endItem;
            end.setType(FieldMarkType.Field_End);
            paragraph.getItems().insert(index + 3, end);
        }

        // Save the document
        document.saveToFile("output/java_with_link.docx", FileFormat.Docx_2013);
        document.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

The core logic is:

  1. Find the target text.

  2. Remove the original text.

  3. Insert a hyperlink field structure at the same position.

  4. Add display text and apply hyperlink formatting.

Key techniques used in this example:

  • Preserve original formatting: copy properties such as font name and font size from the original text.

  • Apply hyperlink style: use blue text and underline, which matches common user expectations.

  • Insert at the correct position: use indexOf() to locate the original text position before replacing it.

Complete Example: Batch Add Hyperlinks to Keywords

The previous sections covered web links, email links, file links, bookmark links, image links, and hyperlinks for existing text. In this section, we combine these ideas into a batch-processing example.

This example scans a technical document and adds official reference links to programming language or technology keywords. After processing, readers can click the keywords directly to open related official resources.

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import com.spire.doc.interfaces.*;
import java.awt.Color;
import java.util.LinkedHashMap;
import java.util.Map;

public class BatchAddHyperlinks {

    /**
     * Add hyperlinks to all matched keyword occurrences in a document.
     */
    public static void addLinksToKeyword(Document document, String keyword, String url) {
        // Find all matched text ranges
        TextSelection[] selections = document.findAllString(keyword, false, true);

        System.out.println("Found " + selections.length + " occurrence(s) of \"" + keyword + "\"");

        // Process from the end to the beginning to avoid index changes
        for (int i = selections.length - 1; i >= 0; i--) {
            try {
                TextRange range = selections[i].getAsOneRange();
                Paragraph paragraph = range.getOwnerParagraph();
                int index = paragraph.getItems().indexOf(range);

                // Skip text that is already inside a hyperlink field
                if (isAlreadyHyperlinked(paragraph, index)) {
                    continue;
                }

                // Use the actual matched text as the display text
                String displayText = range.getText();

                // Remove the original text range
                paragraph.getItems().remove(range);

                // Create a hyperlink at the original position
                createHyperlinkInParagraph(document, paragraph, index, displayText, url, range);

            } catch (Exception e) {
                System.err.println("Error while processing occurrence " + (i + 1) + ": " + e.getMessage());
            }
        }
    }

    /**
     * Check whether the current text range is already inside a hyperlink field.
     */
    private static boolean isAlreadyHyperlinked(Paragraph paragraph, int itemIndex) {
        boolean insideHyperlink = false;

        for (int i = 0; i <= itemIndex; i++) {
            Object item = paragraph.getItems().get(i);

            if (item instanceof Field) {
                Field field = (Field) item;
                if (field.getType() == FieldType.Field_Hyperlink) {
                    insideHyperlink = true;
                }
            } else if (item instanceof FieldMark) {
                FieldMark mark = (FieldMark) item;
                if (mark.getType() == FieldMarkType.Field_End) {
                    insideHyperlink = false;
                }
            }
        }

        return insideHyperlink;
    }

    /**
     * Create a hyperlink field in a paragraph.
     */
    private static void createHyperlinkInParagraph(
        Document document,
        Paragraph paragraph,
        int index,
        String text,
        String url,
        TextRange originalRange
    ) {
        // 1. 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(url);

        paragraph.getItems().insert(index, field);

        // 2. Insert the field separator
        IParagraphBase separator = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark start = (FieldMark) separator;
        start.setType(FieldMarkType.Field_Separator);
        paragraph.getItems().insert(index + 1, start);

        // 3. Insert the display text and preserve part of the original formatting
        ITextRange textRange = new TextRange(document);
        textRange.setText(text);

        if (originalRange != null) {
            textRange.getCharacterFormat().setFontName(
                originalRange.getCharacterFormat().getFontName()
            );
            textRange.getCharacterFormat().setFontSize(
                originalRange.getCharacterFormat().getFontSize()
            );
            textRange.getCharacterFormat().setBold(
                originalRange.getCharacterFormat().isBold()
            );
            textRange.getCharacterFormat().setItalic(
                originalRange.getCharacterFormat().isItalic()
            );
        }

        // Apply a common hyperlink style
        textRange.getCharacterFormat().setTextColor(Color.blue);
        textRange.getCharacterFormat().setUnderlineStyle(UnderlineStyle.Single);

        paragraph.getItems().insert(index + 2, textRange);

        // 4. Insert the field end marker
        IParagraphBase endItem = document.createParagraphItem(ParagraphItemType.Field_Mark);
        FieldMark end = (FieldMark) endItem;
        end.setType(FieldMarkType.Field_End);
        paragraph.getItems().insert(index + 3, end);
    }

    public static void main(String[] args) {
        // Load the Word document
        Document document = new Document();
        document.loadFromFile("input/technical_doc.docx");

        // Define keywords and their corresponding links
        Map<String, String> keywordLinks = new LinkedHashMap<>();
        keywordLinks.put("Java", "https://www.oracle.com/java/");
        keywordLinks.put("Python", "https://www.python.org/");
        keywordLinks.put("Spring Boot", "https://spring.io/projects/spring-boot");
        keywordLinks.put("MySQL", "https://www.mysql.com/");

        // Add hyperlinks in batches
        for (Map.Entry<String, String> entry : keywordLinks.entrySet()) {
            System.out.println("\nProcessing keyword: " + entry.getKey());
            addLinksToKeyword(document, entry.getKey(), entry.getValue());
        }

        // Save the result document
        document.saveToFile("output/doc_with_links.docx", FileFormat.Docx_2013);
        document.dispose();

        System.out.println("\nBatch hyperlink processing completed.");
    }
}
Enter fullscreen mode Exit fullscreen mode

This example does the following:

  • Finds all keyword occurrences in the document

  • Adds the corresponding reference link to each keyword

  • Preserves part of the original text formatting, such as font, size, bold, and italic

  • Applies a common hyperlink style, using blue text and underline

  • Processes matches from the end to the beginning to avoid index shifting

  • Skips text that is already inside a hyperlink field

This structure is suitable for:

  • Automatically generated technical documents

  • API documentation that links class names or method names

  • Help documents that link terms to explanations

  • Report systems that link product names to official pages

Summary

Word hyperlinks can be used for web pages, email addresses, external files, internal bookmarks, and clickable images. By using Java to automate hyperlink creation, you can process long documents, technical manuals, and batch-generated reports more efficiently.

Source: dev.to

arrow_back Back to Tutorials