本文介绍如何使用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();
}
}