Gabe Gabe - 1 year ago 174
Java Question

PDFBox 2.0.3: PDDocument Scratch File Already Closed

I'm generating a PDDocument in Java with code like this...

HashMap<Integer, PDPageContentStream> mPageContentStreamMap = new HashMap<>();
PDDocument doc = new PDDocument();
for (int i = 1; i <= mNumPages; i++) {
PDPage page = new PDPage(PDRectangle.A4);
PDPageContentStream pageContentStream = new PDPageContentStream(doc, page);
contentStreamMap.put(i, pageContentStream);

Then later save and close the document like this...

for (int i : mPageContentStreamMap.keySet()) {

This works fine on the first run; however when I run my program multiple times I get the following error Scratch file already closed
at org.apache.pdfbox.cos.COSStream.createOutputStream(
at org.apache.pdfbox.pdmodel.common.PDStream.createOutputStream(
at org.apache.pdfbox.pdmodel.PDPageContentStream.<init>(
at org.apache.pdfbox.pdmodel.PDPageContentStream.<init>(

If I re-run my program without the "doc.close();" line, this error goes away, but the output of the PDF is duplicated (i.e. a new PDF is generated, but with the content from the last PDF and the content from the current PDF).

Is there a way to close the stream and create multiple PDFs without running into the scratch file error?

Answer Source

I had created a singleton object for my drawing logic meaning after the first run, the same objects were reused when they shouldn't've been, because the input (what was being drawn) had changed.