java - 使用 Java 和 iText 在 PDF 文件中插入附件

标签 java pdf itext

我已经能够编写代码来创建新的 PDF 或打开现有的 PDF 并附加。 我现在想要实现的是在其中插入另一个PDF。以下是我迄今为止编写的用于附加 PDF 的示例代码。

Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();


PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1); 


document.newPage();
cb.addTemplate(page, 0, 0);

// Append sample line
document.add(new Paragraph("my timestamp")); 

document.close();

据我所知,Adobe Reader 确实支持插入文档。不确定是否也可以使用 Java 代码实现相同的目的。

编辑:

下面是我编写的用于在 PDF 中嵌入 PDF 的代码。单击并打开嵌入式 pdf/附件时出现错误。

public class AddEmbeddedFile {
    public static final String SRC = "C:\\Users\\User\\Desktop\\testSource.pdf";
    public static final String Embed = "C:\\Users\\User\\Desktop\\testEmbed.pdf";
    public static final String DEST = "C:\\Users\\User\\Desktop\\testDest.pdf";
    public static void main(String[] args) throws IOException, DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new AddEmbeddedFile().manipulatePdf(SRC, DEST, Embed);
    }
    public void manipulatePdf(String src, String dest, String embed) throws IOException, DocumentException {
        PdfReader reader = new PdfReader(src);
        PdfReader reader2 = new PdfReader(embed);
        int n = reader2.getNumberOfPages();
        reader2.close();
        ByteArrayOutputStream boas;
        byte[] PDFContent = null;
        byte[] PDFContent2 = new byte[0];
        for (int i = 0; i < n; ) {
            reader2.selectPages(String.valueOf(++i));
            boas = new ByteArrayOutputStream();
            PdfStamper stamper2 = new PdfStamper(reader2, boas);
            PDFContent = boas.toByteArray();
            byte[] c = new byte[PDFContent.length + PDFContent2.length];
            System.arraycopy(PDFContent, 0, c, 0, PDFContent.length);
            System.arraycopy(PDFContent2, 0, c, PDFContent.length, PDFContent2.length);
            PDFContent2 = c;
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
        PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
                stamper.getWriter(), null, "tests.pdf", PDFContent2, "pdf", null, 0);
        stamper.addFileAttachment("some test file", fs);
        stamper.close();
    }
}

这是我收到的错误: enter image description here

最佳答案

您在问题中使用的代码是错误的。如果您将 PdfImportedPage 对象导入到 PdfWriter 中,您将失去原始文档中可能存在的所有交互性。您需要改用 PdfStamper

向现有 PDF 添加附件有两种不同的方法。评论中已经提到了一个,您可以引用 AddEmbeddedFile示例:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
            stamper.getWriter(), null, "test.txt", "Some test".getBytes());
    stamper.addFileAttachment("some test file", fs);
    stamper.close();
}

您有一个现有的 PDF src,您在其中嵌入了一个文本文件。调整示例应该相当容易,以便您添加 PDF 字节而不是纯文本。在这种情况下,最终用户只有打开附件面板才能看到 PDF。

附加文件的另一种方法是使用附件注释:

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
        stamper.getWriter(), null, "test.txt", "Some test".getBytes());
    Rectangle rect = new Rectangle(36, 770, 72, 806);
    PdfAnnotation attachment = dfAnnotation.createFileAttachment(
        stamper.getWriter(), rect, "My attachment", fs);
    stamper.addAnnotation(attachment, 1);
    stamper.close();
}

这将在现有 PDF 的第一页上根据 rect 定义的坐标添加可见注释。

您也可能错误地使用了“附加文件”的概念。也许您的意思是看到将一个文件连接到另一个文件。这在我对以下问题的回答中进行了解释:How to merge documents correctly?

更新:

您正在使用此方法创建一个 PdfFileSpecification 实例:

fileEmbedded(
    PdfWriter writer,
    String filePath,
    String fileDisplay,
    byte[] fileStore,
    String mimeType,
    PdfDictionary fileParameter,
    int compressionLevel)

但是你的参数全错了:

PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
    stamper.getWriter(), // correct
    null, // should be "C:\\Users\\User\\Desktop\\testEmbed.pdf"
    "tests.pdf", // correct
    PDFContent2, // this is completely wrong!!!
    "pdf", // should be "application/pdf"
    null, // OK
    0); // choosing 0 means that you don't want to compress the attachment. Why not?

您创建 PdfContent2 的方式完全错误。很难想象您要在这里实现什么。您以完全违反 PDF 引用的方式连接 PDF 字节。

关于java - 使用 Java 和 iText 在 PDF 文件中插入附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32737166/

相关文章:

java - 编写递归下降解析以在 Java 中解析 epsilon(ε)

java - Map 返回 Object 而不是通过后续调用推导

python - Django/xhtml2pdf - 对象没有属性 'encode'

javascript - 在浏览器中创建 PDF : Custom Font

javascript - Itext 或 Adob​​e Acrobat 上的行间距

Itextsharp 7 - 缩放并居中的图像作为水印

java - 用于重命名文件的 Gradle 任务

java - 如何使用 Azure 在 Java 或 Android 中使用 Microsoft Translator API

javascript - 可以通过 Javascript 在 Acrobat 中搜索并保留页面定义区域中的文本

iText - 如何在 pdf 中下移当前内容