【问题标题】:PDFBox: "you did not close a PDFDocument" right after printingPDFBox:打印后“您没有关闭 PDFDocument”
【发布时间】:2019-01-11 05:08:40
【问题描述】:

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

为什么我会收到此警告?

【问题讨论】:

  • 你用的是什么版本?我很惊讶,因为您确实关闭了文档,并且文档对象没有“丢失”。会不会是来自其他代码的另一个文档对象?例如。因为你在其他地方调用了“new PDDocument()”?
  • 我使用的是 PDFBox 2.0.11 版。如果我删除job.print();,消息就会消失。所以我认为该警告与另一个 PDDocument 无关。无论如何,我会检查其余的代码。
  • 另一个想法 - 你在使用什么 jdk / 它是那个数字 (6, 7, 8, 9) 的最新 jdk?
  • 我刚刚从 JDK 1.8.0_131 更新到 1.8.0_181 并且警告消失了。非常感谢您的提示。

标签: java pdf printing pdfbox


【解决方案1】:

正如 cmets 中所讨论的 - 通过更新到最新的 jdk 版本,问题就消失了,这里:从 JDK 1.8.0_131 到 1.8.0_181。我只能怀疑旧的 jdk 有一个错误,即对象被过早地标记为“未使用”并因此被最终确定。

【讨论】:

    【解决方案2】:

    您正在加载 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();
        }
    }
    

    【讨论】:

    • 但是在我做job.print()之前我不能关闭文档;正如您在我的代码中看到的,我在打印后立即关闭了文档(sn-p 中的最后一行),但消息出现在 print 方法中。
    • 谁反对这个,请重新考虑......我个人的态度是,我只反对一个公然无用的答案。虽然这个没有解决问题,但是关于finalization的部分是对的。
    猜你喜欢
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多