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);