In Microsoft Word, we can add hyperlinks to text or images to link to websites, email addresses or even link to specific file. In this article, I will introduce how to add hyperlinks to a Word document programmatically in Java by using Free Spire.Doc for Java API from the following three parts.
Adding hyperlink to Text on Word:
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class WordHyperlink {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();
//Add a section
Section section = document.addSection();
//Add paragraphs to the section
Paragraph para = section.addParagraph();
//Add a web link
para.appendHyperlink("https://google.com/","Click here to Google", HyperlinkType.Web_Link);
//Add an email link
para = section.addParagraph();
para.appendHyperlink("mailto:support@e-iceblue.com", "Contact Google via Email", HyperlinkType.E_Mail_Link);
//Save the document
document.saveToFile("AddTexthyperlinks.docx", FileFormat.Docx);
}
}
Effective screenshot after adding text web link:
Adding hyperlink to image on Word:
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;
public class WordHyperlink {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();
//Add a section
Section section = document.addSection();
//Add paragraphs to the section
Paragraph para = section.addParagraph();
//Add a picture link
para = section.addParagraph();
DocPicture picture = para.appendPicture("logo.png");
para.appendHyperlink("https://google.com/",picture, HyperlinkType.Web_Link);
//Save the document
document.saveToFile("AddhyperlinktoImage.docx", FileFormat.Docx);
}
}
Add hyperlink to link to a specific word file:
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class WordHyperlink {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();
//Add a section
Section section = document.addSection();
//Add paragraphs to the section
Paragraph para = section.addParagraph();
//Add a file link
para = section.addParagraph();
String filePath = "Sample.docx";
para.appendHyperlink(filePath,"Click here to get the details", HyperlinkType.File_Link);
//Save the document
document.saveToFile("AddhyperlinktoFile.docx", FileFormat.Docx);
}
}
Top comments (0)