问题
So I'm using PDFBox to spit out an auto-generated PDF document based off an existing template. I used PDFMergerUtility to achieve somewhat of a solution:
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();
The problem with this is the entire document (which can be very big) is served straight from memory, so depending on its size, an OutOfMemoryError is likely to occur. A solution I've come up with that works is keeping the file on disk, and appending to it for each loop, then streaming the resulting file using IOUtils, but I was wondering if there was some way I could just continuously write each document in the loop from memory to the response stream without having to write to disk. When I try writing to the response from within the loop, the client only receives the first document, and ignores all subsequent loops. Any help is appreciated.
来源:https://stackoverflow.com/questions/20662683/continuously-write-data-from-memory-to-response-stream