本文展示如何使用spire.doc for java在word文档中添加文本超链接和图片超链接。
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.e-iceblue.com/","凯发线上登陆下载网址主页", hyperlinktype.web_link);
//添加邮箱链接
paragraph = section.addparagraph();
paragraph.appendtext("邮箱链接:");
paragraph.appendhyperlink("mailto:support@ e-iceblue.com","support@ e-iceblue.com", 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\\desktop\\logo-2.png");
paragraph.appendhyperlink("https://www.e-iceblue.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);
}
}