问题
We're getting intermittent exceptions from our pdf generator that runs in a docker container in the cloud. One portion of the generator handles taking an SVG document and loading it into a pdf. Every 100ish calls it throws the following exception from importPageAsForm(tmpSVGPdf, 0).
java.io.IOException: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
We haven't been able to reproduce this issue locally.
First we build the pdf that will contain the loaded svg:
PDDocument pdf = new PDDocument();
PDPage page = new PDPage(new PDRectangle(width, height));
pdf.addPage(page);
Then we open a PDF stream & an output stream for the svg transcoder.
try(PDPageContentStream stream = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.APPEND,false, true))
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream())
When we hit importPageAsForm below we pass in the temporary SVG document and somewhere within that function it hits a COSStream that is closed. We run the function locally with the same data and it always works fine.
TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(element.getEncodedData().getBytes()));
TranscoderOutput output = new TranscoderOutput(byteStream);
pdfTranscoder.transcode(input, output);
PDDocument tmpSVGPdf = PDDocument.load(byteStream.toByteArray());
LayerUtility layerUtil = new LayerUtility(pdf);
PDFormXObject svgObj = layerUtil.importPageAsForm(tmpSVGPdf, 0);
stream.drawForm(svgObj);
return Optional.of(pdf);
回答1:
Ok, so in my initial post I actual had 'tmpSVGPdf.close()' This particular line was untested at time of posting which is my fault. It turns out that this was the issue. We weren't closing the tempSVG and for some reason that was causing the problem, despite the fact the close comes after where the exception throws. We inserted close() after the importPageAsForm() call & the issue no longer presents itself. Go figure!
来源:https://stackoverflow.com/questions/53292933/pdfbox-cosstream-closed-before-use