cosstream已关闭,无法读取

pn9klfpd  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(291)

我有下一个代码在我的项目和时间与它落下 COSStream has been closed and cannot be read. Perhaps its enclosing PDDocument has been closed? 它发生在不同的时间和不同的工作量,所以我想修复它。提前谢谢。

public void transferBankActPagesToPdfFile(List<PdfBankActPage> acts, HttpServletResponse response)
            throws IOException {
        try (PDDocument outPDDocument = new PDDocument()) {
            for (PdfBankActPage pdfBankActPage : acts) {
                String templateFilename = TEMPLATES_FOLDER + DELIMETER + pdfBankActPage.getPdfTemplateName();
                PDDocument templatePDDocument = PDDocument.load(readResource(templateFilename));
                PDPage pdPage = templatePDDocument.getPage(0);
                String fontTemplatePath = TEMPLATES_FOLDER + DELIMETER + FONT_TEMPLATE;
                PDDocument fontTemplatePdf = PDDocument.load(readResource(fontTemplatePath));
                PDPage fontTemplatePage = fontTemplatePdf.getPage(0);
                PDResources fontTemplateResources = fontTemplatePage.getResources();
                PDFont cyrillicFont = null;
                for (COSName cosName : fontTemplateResources.getFontNames()) {
                    if (cosName.getName().equals("F4")) {
                        cyrillicFont = fontTemplateResources.getFont(cosName);
                    }
                }
                outPDDocument.addPage(pdPage);
                PDPageContentStream contentStream = new PDPageContentStream(templatePDDocument, pdPage,
                        PDPageContentStream.AppendMode.APPEND, true, true);
                List<PdfTextLine> textLines = pdfBankActPage.getTextLines();
                if (textLines != null) {
                    for (PdfTextLine textLine : textLines) {
                        contentStream.setFont(cyrillicFont, textLine.getFontSize());
                        contentStream.beginText();
                        contentStream.newLineAtOffset(textLine.getOffsetX(), textLine.getOffsetY());
                        contentStream.showText(textLine.getText());
                        contentStream.endText();
                    }
                }
                contentStream.close();
            }
            response.setContentType(MediaType.APPLICATION_PDF_VALUE);
            outPDDocument.save(response.getOutputStream());
        }
    }

这里是加载资源的部分:

private InputStream readResource(String resourceFilename) {
        InputStream inputStream = PdfBankActPagesToPdfFile.class.getResourceAsStream(resourceFilename);
        if (inputStream == null) {
            inputStream = PdfBankActPagesToPdfFile.class.getClassLoader().getResourceAsStream(resourceFilename);
        }
        return inputStream;
    }
dldeef67

dldeef671#

使用模板文档中的流( templatePDDocument , fontTemplatePdf )在每个循环迭代中重新创建并免费进行垃圾收集。因此,在调用之前,这些模板文档中的一些可能已经由垃圾收集完成 outPDDocument.save ,导致您观察到的错误。
如果保留此基本体系结构,则可以通过将这些模板文档全部添加到某个集合并仅在调用 outPDDocument.save .
或者,您可以切换到克隆模板页并使用克隆,而不是使用原始模板页。

相关问题