本文介绍如何使用spire.pdf for java添加普通链接、超文本链接、邮箱链接和文档链接到pdf文档。
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.font.textattribute;
import java.awt.geom.point2d;
import java.awt.geom.rectangle2d;
import java.util.hashmap;
public class addlinkstopdf {
public static void main(string[] args) throws exception {
//创建pdf文档
pdfdocument doc = new pdfdocument();
pdfpagebase page = doc.getpages().add();
//初始化x,y坐标
float y = 30;
float x = 0;
// 创建一个普通字体
pdftruetypefont plainfont = new pdftruetypefont(new font("arial unicode ms",font.plain,13),true);
//创建一个带下划线的字体
hashmap hm = new hashmap();
hm.put(textattribute.underline, textattribute.underline_on);
hm.put(textattribute.size, 13);
hm.put(textattribute.family, "arial");
font font = new font(hm);
pdftruetypefont underlinefont = new pdftruetypefont(font,true);
//添加简单链接到pdf
string label = "简单链接: ";
pdfstringformat format = new pdfstringformat();
format.setmeasuretrailingspaces(true);
page.getcanvas().drawstring(label, plainfont, pdfbrushes.getorange(), 0, y,format);
x = (float)plainfont.measurestring(label,format).getwidth();
page.getcanvas().drawstring("https://www.e-iceblue.com", underlinefont, pdfbrushes.getblue(), x, y 2);
y = y 26;
//添加超文本链接到pdf
label= "超文本链接: ";
page.getcanvas().drawstring(label, plainfont, pdfbrushes.getorange(), 0, y, format);
x = (float)plainfont.measurestring(label,format).getwidth();
pdftextweblink weblink = new pdftextweblink();
weblink.settext("k8凯发天生赢家主页");
weblink.set;
weblink.setfont(plainfont);
weblink.setbrush(pdfbrushes.getblue());
weblink.drawtextweblink(page.getcanvas(), new point2d.float(x, y));
y= y 26;
//添加邮箱链接到pdf
label = "邮箱链接: ";
page.getcanvas().drawstring(label, plainfont, pdfbrushes.getorange(), 0, y, format);
x = (float)plainfont.measurestring(label, format).getwidth();
weblink = new pdftextweblink();
weblink.settext("联系k8凯发天生赢家");
weblink.set;
weblink.setfont(plainfont);
weblink.setbrush(pdfbrushes.getblue());
weblink.drawtextweblink(page.getcanvas(), new point2d.float(x, y));
y = y 26;
//添加文档链接到pdf
label = "文档链接: ";
page.getcanvas().drawstring(label, plainfont, pdfbrushes.getorange(), 0, y, format);
x = (float)plainfont.measurestring(label, format).getwidth();
page.getcanvas().drawstring("打开文件", plainfont, pdfbrushes.getblue(), x, y, format);
rectangle2d rect = new rectangle2d.float(x,y 2,60,15);
pdffilelinkannotation filelinkannotation = new pdffilelinkannotation(rect,"c:\\users\\administrator\\desktop\\image.png");
filelinkannotation.setborder(new pdfannotationborder(0f));
((pdfnewpage) ((page instanceof pdfnewpage) ? page : null)).getannotations().add(filelinkannotation);
//保存文档
doc.savetofile("addlinks.pdf");
doc.close();
}
}