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程序。如下:

 

 

方法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: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);
    }
}

超鏈接添加效果:

 

(本文完)

 

轉載請注明出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM