在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代码

importcom.spire.doc.Document;importcom.spire.doc.FileFormat;importcom.spire.doc.Section;importcom.spire.doc.documents.HorizontalAlignment;importcom.spire.doc.documents.HyperlinkType;importcom.spire.doc.documents.Paragraph;importcom.spire.doc.documents.ParagraphStyle;importcom.spire.doc.fields.DocPicture;publicclassInsertHyperlinks{publicstaticvoidmain(String[]args){//创建Word文档Documentdoc=newDocument();Sectionsection=doc.addSection();//添加网页链接Paragraphparagraph=section.addParagraph();paragraph.appendText("网页链接:");paragraph.appendHyperlink("https://www.baidu.com/","主页",HyperlinkType.Web_Link);//添加邮箱链接paragraph=section.addParagraph();paragraph.appendText("邮箱链接:");paragraph.appendHyperlink("mailto:xxxxx@163.com","xxxxx@163.com",HyperlinkType.E_Mail_Link);//添加文档链接paragraph=section.addParagraph();paragraph.appendText("文档链接:");StringfilePath="C:\\Users\\Administrator\\Desktop\\报表.pdf";paragraph.appendHyperlink(filePath,"点击打开报表",HyperlinkType.File_Link);//添加图片超链接paragraph=section.addParagraph();paragraph.appendText("图片链接:");paragraph=section.addParagraph();DocPicturepicture=paragraph.appendPicture("C:\\Users\\Administrator\\IdeaProjects\\Spire.Doc\\logo(2).jpg");paragraph.appendHyperlink("https://www.baidu.com/",picture,HyperlinkType.Web_Link);//创建段落样式ParagraphStylestyle1=newParagraphStyle(doc);style1.setName("style");style1.getCharacterFormat().setFontName("宋体");doc.getStyles().add(style1);for(inti=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);}}