java - 使用 iText 复制带有注释的 PDF

标签 java pdf itext pdf-annotations

我们需要将现有的多个 PDF 导入一个新的 PDF。部分代码与 iText in Action 2nd edition 第 6.2.1 节中的示例代码类似:

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(
    document, new FileOutputStream(RESULT));
document.open();
PdfPTable table = new PdfPTable(2);
PdfReader reader = new PdfReader(MovieTemplates.RESULT);
int n = reader.getNumberOfPages();
PdfImportedPage page;
for (int i = 1; i <= n; i++) {
    page = writer.getImportedPage(reader, i);
    table.addCell(Image.getInstance(page));
}
document.add(table);
document.close();

但是,我们刚刚意识到在处理带有注释的可填充 PDF 时(在我们的例子中,那些 PDF 已经填充了数据),所有填充的数据都在新 PDF 中丢失了。

我们在本书的同一章节找到了答案:

It's important to understand the difference between resources needed to render the content of a page and the interactive features of a page. In general, these features are called annotations. They include links, text annotations, and form fields. Annotations aren't part of the content stream. They aren't listed in the resources dictionary of the page, but in the annotation dictionary. These interactive features aren't copied when using PdfImportedPage, which means that all interactivity is lost when copying a page with the getImportedPage() method of the PdfWriter class.

但是保留这些注释的解决方案是什么?

最佳答案

作为您提到的那本书的作者,我想指出书中的例子有些过时了。该书将建议您使用 PdfCopyFields 来合并表单,但该类在最新版本的 iText 中已被弃用。

请看一下新的例子:

换句话说:现在可以使用 PdfCopy 类复制/合并表单,但导入它是为了告诉 PdfCopy 字段需要按原样合并在以下代码片段中:

public void createPdf(String filename) throws IOException, DocumentException {
    PdfReader[] readers = {
        new PdfReader(getFile1()),
        new PdfReader(getFile2())
    };
    createPdf(filename, readers);
}

public void createPdf(String filename, PdfReader[] readers)
    throws IOException, DocumentException {
    Document document = new Document();
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
    copy.setMergeFields();
    document.open();
    for (PdfReader reader : readers) {
        copy.addDocument(reader);
    }
    document.close();
    for (PdfReader reader : readers) {
        reader.close();
    }
}

setMergeFields() 方法是您需要记住的方法。

关于java - 使用 iText 复制带有注释的 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26174675/

相关文章:

java - 如何解析某些标签中带有冒号的 XML?

java - 重置 Java 的身份 validator

java - Windows 和 Linux 的应用程序开发

java - 如何检查字体是否可嵌入

java - 使用两个 fragment 库

pdf - 从 PDF 文件中获取 latex 代码

html - 将 PDF 的第一页显示为图像

pdf - 如何将多个 tif 文件合并为单个 tif 文件?

java - 使用 iText 访问智能卡

c# - 如何使用 asp.net c# 直接打印使用 iTextSharp 动态创建的 PDF?