PDFBox:"you did not close a PDFDocument" 打印后

PDFBox: "you did not close a PDFDocument" right after printing

我使用以下 Java 代码打印 PDF 文档:

PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintService(printer);
File file = new File(fileName);
PDDocument doc = PDDocument.load(file);
PDFPageable pageable = new PDFPageable(doc);
job.setPageable(pageable);
System.out.println("-- before printing --");
job.print();
System.out.println("-- after printing --");
doc.close();

控制台上的输出是:

-- before printing --
Aug 03, 2018 12:05:09 PM org.apache.pdfbox.cos.COSDocument finalize
WARNUNG: Warning: You did not close a PDF Document
-- after printing --

为什么我会收到此警告?

您正在加载 PDDocument 但没有关闭它。我怀疑你需要做:

String yourText;
PDDocument yourDocument = PDDocument.load("yourDocument");
try {
    yourText = pdfs.getText(yourDocument);
} finally {
    yourDocument.close();
}

当 pdf 文档完成但尚未关闭时会发出此警告。

请参阅 here 以获取警告:

/**
 * Warn the user in the finalizer if he didn't close the PDF document. The method also
 * closes the document just in case, to avoid abandoned temporary files. It's still a good
 * idea for the user to close the PDF document at the earliest possible to conserve resources.
 * @throws IOException if an error occurs while closing the temporary files
 */
protected void finalize() throws IOException
{
    if (!closed) {
        if (warnMissingClose) {
            log.warn( "Warning: You did not close a PDF Document" );
        }
        close();
    }
}

正如评论中所讨论的那样 - 通过更新到最新的 jdk 版本,问题消失了,在这里:从 JDK 1.8.0_131 到 1.8.0_181 .我只能怀疑旧的 jdk 有一个错误,对象被过早地标记为 "unused" 并因此被最终确定。