本文介紹了COSStream已關閉,無法讀取的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我的項目中有下一個代碼,它不時地落在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;
}
推薦答案
您使用重新創建的模板文檔(templatePDDocument
,fontTemplatePdf
)中的流,并在每次循環迭代中提供免費的垃圾回收。因此,在您調用outPDDocument.save
之前,這些模板文檔中的一些可能已經被垃圾回收完成,從而導致您觀察到的錯誤。
如果保留此基本體系結構,則可以通過將這些模板文檔全部添加到某個集合并僅在調用outPDDocument.save
后清除該集合來防止這些模板文檔過早定版。
或者,您也可以切換到克隆模板頁面并使用克隆,而不是使用原始模板頁面。
這篇關于COSStream已關閉,無法讀取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,