Java 添加超連接到Word文檔

對特定元素添加超連接後,用戶能夠經過點擊被連接的元素來激活這些連接,一般在被連接的元素下帶有下劃線或者以不一樣的顏色顯示來進行區分。按照使用對象的不一樣,連接能夠分爲文本超連接,圖像超連接,E-mail連接,錨點連接,多媒體文件連接,空連接等多種連接,本篇文章中將介紹在Word中添加如下幾種常見超連接的方法,包括:html

1. 網頁連接java

 1.1 給文本添加網頁連接app

 1.2 給圖片添加網頁連接maven

2. 添加文檔連接工具

3. E-mail郵箱連接測試

 

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

Jar文件獲取及導入:code

方法1官網獲取jar文件包。下載並解壓文件。解壓後,將文件夾lib下的Spire.Doc.jar文件導入Java程序。以下:orm

 

 

方法2經過maven倉庫安裝導入。htm

 

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:zzhuang@163.com","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);
    }
}

超連接添加效果:

 

(本文完)

 

轉載請註明出處!