文本介绍如何使用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("arial unicode ms", font.plain, 12)));
//设置文档权限为禁止更改
signature.setdocumentpermissions(pdfcertificationflags.forbid_changes);
signature.setcertificated(true);
//保存文档
doc.savetofile("output/addsignature.pdf");
doc.close();
}
}