通过 Java 向 PDF 添加数字签名

使用服务器端 Aspose.PDF 为 Java API 生成和验证数字签名。原生和高性能库

如何使用 Java 工具向 PDF 文件添加数字签名

為了添加數位簽名,我們將使用[Aspose.PDF用於Java](https://products.aspose.com/pdf/java)API,這是一個功能豐富,功能強大且易於使用的Java轉換API平臺。您可以直接從 [Maven](https://repository.aspose.com/webapp/#/artifacts/browse/tree/General/repo/com/aspose/aspose-pdf)下載其最新版本,並通過將以下配置添加到 pom.xml 來將其安裝在基於 Maven 的專案中。

Repository

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

通過Java將數位簽名添加到 PDF


您需要 [Aspose.PDF for Java](https://releases.aspose.com/pdf/java)來嘗試環境中的代碼。

  1. 使用 Document 實例載入 PDF。
  2. 載入所有 PDF 文件,並指定其完整路徑。
  3. 設定文字樣式,例如字體、字號、顏色等。
  4. 儲存 PDF 文件,您將獲得已插入簽署的文件。
  5. 使用 PdfFileSignature.VerifySigned() 方法驗證簽章的有效性。

使用-Java 向 PDF 文件添加电子签名

此示例代码说明如何为 PDF 页面签名-Java

Input file:

File not added

Certificate file:

File not added

Output format:

Output file:

String inFile = DATA_DIR.resolve("DigitallySign.pdf").toString();
String outFile = DATA_DIR.resolve("DigitallySign_out.pdf").toString();
String pfxFile = DATA_DIR.resolve("test.pfx").toString();
Document pdfDocument = new Document(inFile);

PdfFileSignature signature = new PdfFileSignature(pdfDocument);

PKCS7 pkcs = new PKCS7(pfxFile, "Pa$$w0rd2020");
// Use PKCS7/PKCS7Detached
// objects
signature.sign(1, true, new java.awt.Rectangle(300, 100, 400, 200), pkcs);
// Save output PDF file
signature.save(outFile);
// Close the signature object
signature.close();
// Close the document
pdfDocument.close();