1.引入依赖
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>2.6.3</version>
</dependency>
</dependencies>
2.代码
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTrueTypeFont;
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 ImageSignature {
public static void main(String[] args) {
//加载PDF文档
PdfDocument doc = new PdfDocument();
doc.loadFromFile("D:\\keytest\\7.pdf");
//加载pfx证书
PdfCertificate cert = new PdfCertificate("D:\\keytest\\keystore.p12", "123456");
//添加数字签名,设置其位置和大小
PdfSignature signature = new PdfSignature(doc, doc.getPages().get(doc.getPages().getCount() - 1), cert, "MySignature");
Rectangle2D rect = new Rectangle2D.Float();
rect.setFrame(new Point2D.Float((float) doc.getPages().get(0).getActualSize().getWidth() - 250, (float) doc.getPages().get(0).getActualSize().getHeight() - 300), new Dimension(170, 150));
signature.setBounds(rect);
//设置签名为图片形式
signature.setGraphicMode(GraphicMode.Sign_Image_Only);
signature.setSignImageSource(PdfImage.fromFile("D:\\keytest\\qm.png"));
//设置文档权限为禁止更改
//signature.setDocumentPermissions(PdfCertificationFlags.Forbid_Changes);
//signature.setCertificated(true);
//保存文档
doc.saveToFile("D:\\keytest\\8.pdf");
doc.close();
}
}