Java adds hyperlinks to Word documents

After adding hyperlinks to specific elements, users can activate these links by clicking on the linked elements, usually with underlines under the linked elements or by displaying them in different colors. According to the different objects used, links can be divided into text hyperlinks, image hyperlinks, E-mail links, anchor links, multimedia file links, empty links and other links. This article will introduce the following common ways to add hyperlinks to Word, including:

1. Web Links

1.1 Adding Web Links to Text

1.2 Adding Web Links to Pictures

2. Add document links

3. E-mail links


Use Tools: Free Spire.Doc for Java (Free Edition)

Jar file acquisition and import:

Method 1: Official Access Jar file packages. Download and unzip the file. After decompression, import the Spire.Doc.jar file under the folder lib into the Java program. As follows:



Method 2: Through maven Warehouse Installation Import.


Java code example (for reference)

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

public class AddHyperlink {
    public static void main(String[]args){
        //create documents
        Document doc = new Document();
        Section section = doc.addSection();

        //Add Web links to text
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Page Links:");
        paragraph.appendHyperlink("","HomePage", HyperlinkType.Web_Link);

        //Add hyperlinks to images
        paragraph = section.addParagraph();
        paragraph.appendText("Picture Links:");
        paragraph = section.addParagraph();
        DocPicture picture = paragraph.appendPicture("code.png");
        paragraph.appendHyperlink("",picture, HyperlinkType.Web_Link);

        //Add mailbox links
        paragraph = section.addParagraph();
        paragraph.appendText("Mailbox links:");
        paragraph.appendHyperlink("","zzhuang@", HyperlinkType.E_Mail_Link);

        //Add document links
        paragraph = section.addParagraph();
        paragraph.appendText("Document links:");
        String filePath = "C:\\Users\\Administrator\\Desktop\\Test documentation\\sample.docx";
        paragraph.appendHyperlink(filePath,"Click to view the original document", HyperlinkType.File_Link);

        //Create paragraph style
        ParagraphStyle style1 = new ParagraphStyle(doc);

        for (int i = 0; i < section.getParagraphs().getCount(); i++) {
            //Centralize the paragraph
            //Automatically add intervals at the end of a paragraph
            //Applying paragraph style

        //Save Documents
        doc.saveToFile("AddHyperlinks.docx", FileFormat.Docx_2013);

Hyperlink add effect:


(End of this article)


Reprinted please indicate the source!

Tags: Java Maven

Posted on Thu, 10 Oct 2019 00:24:56 -0700 by j_70