Java关闭PDF错误

时间:2011-02-11 11:31:27

标签: java pdf pdfbox

我有这个java代码:

try {
    PDFTextStripper pdfs = new PDFTextStripper();

    String textOfPDF = pdfs.getText(PDDocument.load("doc"));

    doc.add(new Field(campo.getDestino(),
            textOfPDF,
            Field.Store.NO,
            Field.Index.ANALYZED));

} catch (Exception exep) {
    System.out.println(exep);
    System.out.println("PDF fail");
}

抛出这个:

11:45:07,017 WARN  [COSDocument] Warning: You did not close a PDF Document

我不知道为什么要扔掉这个1,2,3或更多。

我发现COSDocument是一个类并且有close()方法,但是我没有使用这个类。

我有这个导入:

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

谢谢:)

3 个答案:

答案 0 :(得分:13)

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

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

答案 1 :(得分:7)

也遇到了这个问题。使用Java 7,您可以这样做:

try(PDDocument document = PDDocument.load(input)) {
  // do something  
} catch (IOException e) {
  e.printStackTrace();
}

由于PDDocument implements Closeabletry块会在最后自动调用其close()方法。

答案 2 :(得分:4)

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

以下是来自COSDocumentfinalize方法:

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

要摆脱此警告,您应该在完成后明确调用文档上的close