0

我一直在使用 PDFBox 试图根据现有模板吐出自动生成的 PDF。下面的代码因finalDoc.save()IndexOutOfBoundsException 而失败,我不确定我做错了什么。

PDDocument finalDoc = new PDDocument(); 
for (StudentEN student : students) {
    PDDocument document = PDDocument.load("template.pdf");
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
    PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

    contentStream.beginText();
    // Draw stuff
    contentStream.endText();

    contentStream.close();
    finalDoc.addPage(page);
    document.close();
}

finalDoc.save(response.getOutputStream());
finalDoc.close();

任何帮助是极大的赞赏!

4

1 回答 1

4

PDFMergerUtility 为我完成了这项工作:

PDFMergerUtility finalDoc = new PDFMergerUtility(); 
for (StudentEN student : students) {
    PDDocument document = PDDocument.load("template.pdf");
    PDPage page = (PDPage) document.getDocumentCatalog().getAllPages().get(0);
    PDPageContentStream contentStream = new PDPageContentStream(document, page, true, true);

    contentStream.beginText();
    // Draw stuff
    contentStream.endText();

    contentStream.close();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    document.save(out);
    finalDoc.addSource(new ByteArrayInputStream(out.toByteArray()));
    document.close();
}

response.setContentType("application/pdf");
finalDoc.setDestinationStream(response.getOutputStream());
finalDoc.mergeDocuments();
于 2013-11-07T15:34:46.430 回答