Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java close PDF error

Tags:

java

pdf

pdfbox

I have this java code:

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");
}

And throws this:

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

And I don't know why but throw this 1, 2, 3, or more.

I find that COSDocument is a class and have close() method, but I don't use this class nowhere.

I have this imports:

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

Thanks :)

like image 837
bonsai Avatar asked Feb 11 '11 11:02

bonsai


2 Answers

You're loading a PDDocument but not closing it. I suspect you need to do:

String textOfPdf;
PDDocument doc = PDDocument.load("doc");
try {
    textOfPdf = pdfs.getText(doc);
} finally {
    doc.close();
}
like image 50
Jon Skeet Avatar answered Oct 19 '22 16:10

Jon Skeet


Just had this issue, too. With Java 7 you can do this:

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

Because PDDocument implements Closeable, the try block will automagically call its close() method at the end.

like image 28
Benjamin M Avatar answered Oct 19 '22 18:10

Benjamin M