In general, when editing a Word document, inserting hyperlinks in specific text or images allows users to quickly jump to other target locations or web pages. In today's article, I'll show you how to use Free Spire.Doc for Java to add text and image hyperlinks to your Word documents.
** Import JAR package ** ** Method 1: ** Download Free Spire.Doc for Java, unzip it, and in the lib folder Import the Spire.Doc.jar package into your Java application as a dependency. ** Method 2: ** Install the JAR package via the Maven repository and configure the pom.xml file as follows:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>
** Java code **
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.google.com/", "home page", HyperlinkType.Web_Link);
//Insert email link
paragraph = section.addParagraph();
paragraph.appendText("Email link: ");
paragraph.appendHyperlink("mailto:[email protected]", "[email protected]", HyperlinkType.E_Mail_Link);
//Insert a 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 hyperlink: ");
paragraph = section.addParagraph();
DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\IdeaProjects\\Spire.Doc\\logo (2).jpg ");
paragraph.appendHyperlink("https://www.google.com/", picture, HyperlinkType.Web_Link);
for (int i = 0; i < section.getParagraphs().getCount(); i++) {
//Center paragraph
section.getParagraphs().get(i).getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
//Automatically add spaces at the end of paragraphs
section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
//Save to file
doc.saveToFile("InsertHyperlinks.docx", FileFormat.Docx_2013);
}
}
}
Recommended Posts