本文介绍如何使用spire.pdf for java为pdf文档添加数字签名时添加一个可信时间戳。
import com.spire.pdf.pdfdocument;
import com.spire.pdf.graphics.*;
import com.spire.pdf.security.graphicmode;
import com.spire.pdf.security.pdfcertificate;
import com.spire.pdf.security.pdfcertificationflags;
import com.spire.pdf.security.pdfsignature;
import java.awt.*;
import java.awt.geom.point2d;
import java.awt.geom.rectangle2d;
public class signwithtimestamp {
public static void main(string[] args) {
//加载pdf文档
pdfdocument doc = new pdfdocument();
doc.loadfromfile("c:\\users\\administrator\\desktop\\introduction.pdf");
//加载pfx文档
pdfcertificate cert = new pdfcertificate("c:\\users\\administrator\\desktop\\gary.pfx", "e-iceblue");
//添加数字签名,设置其位置和大小
pdfsignature signature = new pdfsignature(doc, doc.getpages().get(0), cert, "mysignature");
rectangle2d rect = new rectangle2d.float();
rect.setframe(new point2d.float((float) doc.getpages().get(0).getactualsize().getwidth() - 220, (float) doc.getpages().get(0).getactualsize().getheight() - 140), new dimension(200, 100));
signature.setbounds(rect);
//设置签名为文本模式
signature.setgraphicmode(graphicmode.sign_detail);
//设置签名的内容
signature.setnamelabel("签字者:");
signature.setname("gary");
signature.setcontactinfolabel("联系电话:");
signature.setcontactinfo("02881705109");
signature.setlocationinfolabel("地点:");
signature.setlocationinfo("成都");
signature.setreasonlabel("原因:");
signature.setreason("我是文档所有者");
//设置签名的字体
signature.setsigndetailsfont(new pdftruetypefont(new font("宋体", font.plain, 12)));
//设置文档权限为禁止更改
signature.setdocumentpermissions(pdfcertificationflags.forbid_changes);
signature.setcertificated(true);
//配置时间戳服务器
string timestampeserverurl = "http://timestamp.digicert.com";
signature.configuretimestamp(timestampeserverurl);
//保存文档
doc.savetofile("output/timestamp.pdf");
doc.close();
}
}