Java PDFBox:“一份文件”;您没有关闭PDFDocument“;刚印完

Java PDFBox:“一份文件”;您没有关闭PDFDocument“;刚印完,java,pdf,printing,pdfbox,Java,Pdf,Printing,Pdfbox,我使用以下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.

我使用以下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文档完成且尚未关闭时发出

有关警告信息,请参阅:

/**
 * 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有一个bug,即对象被过早地标记为“未使用”,从而被最终确定。

您使用的是什么版本?我很惊讶,因为您确实关闭了文档,并且文档对象没有“丢失”。是否有来自其他代码的另一个文档对象?例如,因为您在其他地方调用了“new PDDocument()”?我使用PDFBox的2.0.11版。如果我删除
job.print()消息消失。因此,我认为该警告与另一个PDI文档无关。我将检查其余的代码。另一个想法-您使用的是什么jdk/它是该数字(6、7、8、9)的最新jdk吗?我刚刚从jdk 1.8.0_131更新到1.8.0_181,警告消失了。非常感谢您的提示。但我无法在执行作业之前关闭文档。print();正如您在我的代码中看到的,我在打印后立即关闭了文档(代码段的最后一行),但消息出现在print方法中。无论是谁否决了这一点,请重新考虑。。。我个人的态度是,我只是否决了一个毫无用处的答案。虽然这一部分没有解决问题,但关于定稿的部分是正确的。