通过 Java 向 PDF 添加数字签名

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

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

為了新增數位簽名,我們將使用 Aspose.PDF for Java API,這是一個功能豐富、強大且易於使用的 Java 平台轉換 API。您可以直接從 Maven 下載其最新版本,並透過在 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 才能在您的環境中測試程式碼。

  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();