文本介绍如何使用Spire.PDF for Java在PDF文档中添加数字签名(或电子签章)。
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 AddDigitalSignature {
public static void main(String[] args) {
//加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.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() - 340, (float) doc.getPages().get(0).getActualSize().getHeight() - 150), new Dimension(270, 100));
signature.setBounds(rect);
//设置签名为图片加文本模式
signature.setGraphicMode(GraphicMode.Sign_Image_And_Sign_Detail);
//设置签名的内容
signature.setNameLabel("签字者:");
signature.setName("Gary");
signature.setContactInfoLabel("联系电话:");
signature.setContactInfo("02881705109");
signature.setDateLabel("日期:");
signature.setDate(new java.util.Date());
signature.setLocationInfoLabel("地点:");
signature.setLocationInfo("成都");
signature.setReasonLabel("原因:");
signature.setReason("我是文档所有者");
signature.setDistinguishedNameLabel("DN: ");
signature.setDistinguishedName(signature.getCertificate().get_IssuerName().getName());
signature.setSignImageSource(PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\logo-2.png"));
//设置签名的字体
signature.setSignDetailsFont(new PdfTrueTypeFont(new Font("宋体", Font.PLAIN, 12)));
//设置文档权限为禁止更改
signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
signature.setCertificated(true);
//保存文档
doc.saveToFile("output/AddSignature.pdf");
doc.close();
}
}