PDFBox COSStream closed before use

爱⌒轻易说出口 提交于 2021-02-11 14:45:13

问题


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

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