我一直在使用 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();
非常感谢任何帮助!
最佳答案
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();
关于java - 使用现有 PDF 作为模板创建具有多个页面的新 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821800/