Continuously write data from memory to response stream

杀马特。学长 韩版系。学妹 提交于 2019-12-11 10:31:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!