天天看點

Java 添加超連結到Word文檔

對特定元素添加超連結後,使用者可以通過點選被連結的元素來激活這些連結,通常在被連結的元素下帶有下劃線或者以不同的顔色顯示來進行區分。按照使用對象的不同,連結可以分為文本超連結,圖像超連結,E-mail連結,錨點連結,多媒體檔案連結,空連結等多種連結,本篇文章中将介紹在Word中添加以下幾種常見超連結的方法,包括:

1. 網頁連結

 1.1 給文本添加網頁連結

 1.2 給圖檔添加網頁連結

2. 添加文檔連結

3. E-mail郵箱連結

使用工具:Free Spire.Doc for Java (免費版)

Jar檔案擷取及導入:

方法1:官網擷取jar檔案包。下載下傳并解壓檔案。解壓後,将檔案夾lib下的Spire.Doc.jar檔案導入Java程式。如下:

Java 添加超連結到Word文檔

方法2:通過maven倉庫安裝導入。

Java代碼示例(供參考)

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.DocPicture;

public class AddHyperlink {
    public static void main(String[]args){
        //建立文檔
        Document doc = new Document();
        Section section = doc.addSection();

        //給文字添加網頁連結
        Paragraph paragraph = section.addParagraph();
        paragraph.appendText("網頁連結:");
        paragraph.appendHyperlink("https://www.baidu.com/","HomePage", HyperlinkType.Web_Link);

        //給圖檔添加網頁超連結
        paragraph = section.addParagraph();
        paragraph.appendText("圖檔連結:");
        paragraph = section.addParagraph();
        DocPicture picture = paragraph.appendPicture("code.png");
        picture.setTextWrappingStyle(TextWrappingStyle.Inline);
        paragraph.appendHyperlink("https://baike.baidu.com/item/Java/85979?fr=aladdin",picture, HyperlinkType.Web_Link);

        //添加郵箱連結
        paragraph = section.addParagraph();
        paragraph.appendText("郵箱連結:");
        paragraph.appendHyperlink("mailto:[email protected]","zzhuang@ 163.com", HyperlinkType.E_Mail_Link);

        //添加文檔連結
        paragraph = section.addParagraph();
        paragraph.appendText("文檔連結:");
        String filePath = "C:\\Users\\Administrator\\Desktop\\測試文檔\\sample.docx";
        paragraph.appendHyperlink(filePath,"點選檢視原文檔", HyperlinkType.File_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.Left);
            //段落末尾自動添加間隔
            section.getParagraphs().get(i).getFormat().setAfterAutoSpacing(true);
            //應用段落樣式
            section.getParagraphs().get(i).applyStyle(style1.getName());
        }

        //儲存文檔
        doc.saveToFile("AddHyperlinks.docx", FileFormat.Docx_2013);
    }
}      

超連結添加效果:

Java 添加超連結到Word文檔

(本文完)

轉載請注明出處!