cosstream已关闭,无法读取

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

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

  1. public void transferBankActPagesToPdfFile(List<PdfBankActPage> acts, HttpServletResponse response)
  2. throws IOException {
  3. try (PDDocument outPDDocument = new PDDocument()) {
  4. for (PdfBankActPage pdfBankActPage : acts) {
  5. String templateFilename = TEMPLATES_FOLDER + DELIMETER + pdfBankActPage.getPdfTemplateName();
  6. PDDocument templatePDDocument = PDDocument.load(readResource(templateFilename));
  7. PDPage pdPage = templatePDDocument.getPage(0);
  8. String fontTemplatePath = TEMPLATES_FOLDER + DELIMETER + FONT_TEMPLATE;
  9. PDDocument fontTemplatePdf = PDDocument.load(readResource(fontTemplatePath));
  10. PDPage fontTemplatePage = fontTemplatePdf.getPage(0);
  11. PDResources fontTemplateResources = fontTemplatePage.getResources();
  12. PDFont cyrillicFont = null;
  13. for (COSName cosName : fontTemplateResources.getFontNames()) {
  14. if (cosName.getName().equals("F4")) {
  15. cyrillicFont = fontTemplateResources.getFont(cosName);
  16. }
  17. }
  18. outPDDocument.addPage(pdPage);
  19. PDPageContentStream contentStream = new PDPageContentStream(templatePDDocument, pdPage,
  20. PDPageContentStream.AppendMode.APPEND, true, true);
  21. List<PdfTextLine> textLines = pdfBankActPage.getTextLines();
  22. if (textLines != null) {
  23. for (PdfTextLine textLine : textLines) {
  24. contentStream.setFont(cyrillicFont, textLine.getFontSize());
  25. contentStream.beginText();
  26. contentStream.newLineAtOffset(textLine.getOffsetX(), textLine.getOffsetY());
  27. contentStream.showText(textLine.getText());
  28. contentStream.endText();
  29. }
  30. }
  31. contentStream.close();
  32. }
  33. response.setContentType(MediaType.APPLICATION_PDF_VALUE);
  34. outPDDocument.save(response.getOutputStream());
  35. }
  36. }

这里是加载资源的部分:

  1. private InputStream readResource(String resourceFilename) {
  2. InputStream inputStream = PdfBankActPagesToPdfFile.class.getResourceAsStream(resourceFilename);
  3. if (inputStream == null) {
  4. inputStream = PdfBankActPagesToPdfFile.class.getClassLoader().getResourceAsStream(resourceFilename);
  5. }
  6. return inputStream;
  7. }
dldeef67

dldeef671#

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

相关问题