Insert Hyperlinks in Word in Java

This article demonstrates how to add a text hyperlink, an image hyperlink, an email link and a file link to a Word document using Spire.Doc for Java.

Code Snippets

import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.documents.HorizontalAlignment;
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();
        Section section = doc.addSection();

        //insert web link
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("Web Link: ");
        paragraph.appendHyperlink("https://www.e-iceblue.com/","Home Page", HyperlinkType.Web_Link);

        //insert email link
        paragraph = section.addParagraph();
        paragraph.appendText("Email Link: ");
        paragraph.appendHyperlink("mailto:support@e-iceblue.com","support@e-iceblue.com", HyperlinkType.E_Mail_Link);

        //insert file link
        paragraph = section.addParagraph();
        paragraph.appendText("File Link: ");
        paragraph.appendHyperlink("C:\\Users\\Administrator\\Desktop\\Report.pdf","Click to open Report.pdf", HyperlinkType.File_Link);

        //insert image hyperlink
        paragraph = section.addParagraph();
        paragraph.appendText("Image Hyper Link: ");
        paragraph = section.addParagraph();
        DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\Desktop\\logo-2.png");
        paragraph.appendHyperlink("https://www.e-iceblue.com/",picture, HyperlinkType.Web_Link);

        for (int i = 0; i < section.getParagraphs().getCount(); i++) {

            //align paragraph to center
            section.getParagraphs().get(i).getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            //add auto spacing after paragraph
            section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
        }

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

Output

Insert Hyperlinks in Word in Java