首页 > 解决方案 > PDFBox:打印后“您没有关闭 PDFDocument”

问题描述

我使用以下 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 --

为什么我会收到此警告?

标签: javapdfprintingpdfbox

解决方案


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

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

当 pdf 文档最终确定且尚未关闭时,会发出此警告。

请参阅此处以获取警告:

/**
 * 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();
    }
}

推荐阅读