【发布时间】:2019-04-16 23:46:06
【问题描述】:
我们的 pdf 生成器在云中的 docker 容器中运行,出现间歇性异常。生成器的一部分处理获取 SVG 文档并将其加载到 pdf 中。每 100 次调用它都会引发以下异常 importPageAsForm(tmpSVGPdf, 0).
java.io.IOException: COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed?
我们无法在本地重现此问题。
首先我们构建包含加载的 svg 的 pdf:
PDDocument pdf = new PDDocument();
PDPage page = new PDPage(new PDRectangle(width, height));
pdf.addPage(page);
然后我们为 svg 转码器打开一个 PDF 流和一个输出流。
try(PDPageContentStream stream = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.APPEND,false, true))
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream())
当我们点击下面的 importPageAsForm 时,我们传入了临时 SVG 文档,并且在该函数中的某处它点击了一个关闭的 COSStream。我们使用相同的数据在本地运行该函数,它始终可以正常工作。
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);
【问题讨论】:
-
我怀疑你关闭 tmpSVGPdf 太早了,可能目标文档中使用了一些对象,尽管
importPageAsForm应该进行正确的克隆。还要确保您使用的是最新的 PDFBox 版本,您使用的是哪一个?