Java/ Insert Hyperlinks in Word Documents

In a Word document, a hyperlink refers to a link inserted in the specific text or picture, which enables you to jump between different text elements in a document or between different websites. This article will demonstrate how to add a text hyperlink, an image hyperlink, an email link and a file link to a Word document with a 3rd party free API.

Method 1: Download the Free Spire.Doc for Java and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.


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("", "Home Page", HyperlinkType.Web_Link);

//insert email link
paragraph = section.addParagraph();
paragraph.appendText("Email Link: ");
paragraph.appendHyperlink("", "", HyperlinkType.E_Mail_Link);

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

//insert image hyperlink
paragraph = section.addParagraph();
paragraph.appendText("Image Hyper Link: ");
paragraph = section.addParagraph();
DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\IdeaProjects\\Spire.Doc\\logo (2).jpg");
paragraph.appendHyperlink("", picture, HyperlinkType.Web_Link);

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

//align paragraph to center
//add auto spacing after paragraph

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

Sharing Java Code

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store