如何使用 Java (IText API) 在不丢失数字签名的情况下合并 PDF

How to merge PDFs without losing digital signature using Java (IText API)

我有一个经过数字签名的 pdf 文档,我想使用 java itext api 将这个经过数字签名的 Pdf 附加到另一个普通 pdf 上,这可能吗? 我试图将包含数字签名的 pdf 附加到另一个。我能够合并 pdf,但最终的 pdf 未在输出 pdf 文件中保留数字签名。可以吗?.

这是不可能的,这个数字签名是专门为保护原始文档不被以任何方式修改而设计的。

要合并并签署这两个文档,您需要知道用于签名的密钥并为新的合并文档再次生成签名。

正如其他人已经指出的那样,签名背后的想法(至少是想法的主要部分)是为了确保文档没有被更改。另一方面,合并确实会更改文档。因此,合并将破坏签名。

不过,另一种方法是将另一个“普通”PDF 制作成可移植的 collection(一种带有附件的特殊 PDF)并将签名的 PDF 附加到 collection .

从 collection 打开签名的 PDF 时,签名将与原始签名的 PDF 一样完好无损。

创建可移植文件的示例代码collection

您可以在 iText 网站上找到可移植 collection 创建的示例:

public static final String DEST = "results/collections/portable_collection.pdf";
public static final String DATA = "resources/data/united_states.csv";
public static final String HELLO = "resources/pdfs/hello.pdf";
public static final String IMG = "resources/images/berlin2013.jpg";

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    document.add(new Paragraph("Portable collection"));
    PdfCollection collection = new PdfCollection(PdfCollection.TILE);
    writer.setCollection(collection);
    PdfFileSpecification fileSpec = PdfFileSpecification.fileEmbedded(
            writer, DATA, "united_states.csv", null);
    writer.addFileAttachment("united_states.csv", fileSpec);
    fileSpec = PdfFileSpecification.fileEmbedded(
            writer, HELLO, "hello.pdf", null);
    writer.addFileAttachment("hello.pdf", fileSpec);
    fileSpec = PdfFileSpecification.fileEmbedded(
            writer, IMG, "berlin2013.jpg", null);
    writer.addFileAttachment("berlin2013.jpg", fileSpec);
    document.close();
}

(here on the web site, here 在他们的 github)

该示例的 运行 结果是 here

(由于您使用的是 itext 标签而不是 itext7 标签,因此我假设您使用的是 iText 版本 5。5.x。)

  1. 在 Adob​​e 中打开签名的 pdf。

  2. 打开打印对话框(Ctrl+P)

  3. 将打印机更改为“Microsoft Print to PDF”然后打印。

  4. 新创建的 PDF 将具有签名,并且在 combine/merge 活动中将作为普通 pdf 运行。

注意:此方法将签名文档转换为标准 pdf。结果显示签名信息,但底层数字签名丢失。在我的例子中,原始签名者理解其中的区别。

创建摘要文件是我的目标。我将各种经过数字签名的文档以及其他相关文档合并到一个摘要 pdf 中。存储原始的、数字签名的文档以供将来参考。我越来越相信,不可能将经过数字签名的文档组合成一个单一的摘要 pdf,同时保持基础数字签名。

需要摘要数据包的用户将从我建议的方法中受益。请记住,只要原始数字签名文档可按需提供,我的方法仍然是“合法有效的”。