1. 程式人生 > 實用技巧 >Java 新增超連結到 Word 文件

Java 新增超連結到 Word 文件

在Word文件中,超連結是指在特定文字或者圖片中插入的能跳轉到其他位置或網頁的連結,它也是我們在編輯製作Word文件時廣泛使用到的功能之一。今天這篇文章就將為大家演示如何使用Free Spire.Doc for Java在Word文件中新增文字超連結和圖片超連結。

Jar包匯入

方法一:下載Free Spire.Doc for Java包並解壓縮,然後將lib資料夾下的Spire.Doc.jar包作為依賴項匯入到Java應用程式中。

方法二:通過Maven倉庫安裝JAR包,配置pom.xml檔案的程式碼如下

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>http://
repo.e-iceblue.cn/repository/maven-public/</url> </repository> </repositories> <dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>2.7.3</version> </dependency> </dependencies>

Java程式碼

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.documents.ParagraphStyle;
import
com.spire.doc.fields.DocPicture; public class InsertHyperlinks { public static void main(String[] args) { //建立Word文件 Document doc = new Document(); Section section = doc.addSection(); //新增網頁連結 Paragraph paragraph = section.addParagraph(); paragraph.appendText("網頁連結:"); paragraph.appendHyperlink("https://www.baidu.com/","主頁", HyperlinkType.Web_Link); //新增郵箱連結 paragraph = section.addParagraph(); paragraph.appendText("郵箱連結:"); paragraph.appendHyperlink("mailto:[email protected]","[email protected]", HyperlinkType.E_Mail_Link); //新增文件連結 paragraph = section.addParagraph(); paragraph.appendText("文件連結:"); String filePath = "C:\\Users\\Administrator\\Desktop\\報表.pdf"; paragraph.appendHyperlink(filePath,"點選開啟報表", HyperlinkType.File_Link); //新增圖片超連結 paragraph = section.addParagraph(); paragraph.appendText("圖片連結:"); paragraph = section.addParagraph(); DocPicture picture = paragraph.appendPicture("C:\\Users\\Administrator\\IdeaProjects\\Spire.Doc\\logo (2).jpg"); paragraph.appendHyperlink("https://www.baidu.com/",picture, HyperlinkType.Web_Link); //建立段落樣式 ParagraphStyle style1 = new ParagraphStyle(doc); style1.setName("style"); style1.getCharacterFormat().setFontName("宋體"); doc.getStyles().add(style1); for (int i = 0; i < section.getParagraphs().getCount(); i++) { //將段落居中 section.getParagraphs().get(i).getFormat().setHorizontalAlignment(HorizontalAlignment.Center); //段落末尾自動新增間隔 section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true); //應用段落樣式 section.getParagraphs().get(i).applyStyle(style1.getName()); } //儲存文件 doc.saveToFile("InsertHyperlinks.docx", FileFormat.Docx_2013); } }