我一直在使用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();
非常感谢任何帮助!
答案 0 :(得分:3)
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();