0

I can't delete pdf file after working with PdfBox. All closeable variables are closed, but it not helped. I can't delete pdf file anywhere and anyhow, when my app launch method with PdfBox library.

public void generateTxtFromPDF(String txtFile, String pdfFile) throws IOException {
    COSDocument cosDoc = null;
    PDDocument document = null;
    PrintWriter pw = null;
    try {
        File f = new File(pdfFile);
        String parsedText;
        PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
        parser.parse();
        cosDoc = parser.getDocument();
        PDFTextStripper pdfStripper = new PDFTextStripper();
        document = new PDDocument(cosDoc);
        parsedText = pdfStripper.getText(document);
        pw = new PrintWriter(txtFile);
        pw.print(parsedText);
    } catch (IOException e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        if (pw != null) {
            pw.close();
        }
        if (document != null) {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (cosDoc != null) {
            cosDoc.close();
        }
    }
}

maybe, somebody know what is wrong?

1 Answers1

0

I fixed this problem - change JDK version (jdk1.8.0_181 => jdk1.8.0_221). Thanks for interest for my problem. And use this code:

    public void generateTxtFromPDF(String txtFile, String pdfFile) throws IOException {
    File f = new File(pdfFile);
    String parsedText;
    PDFParser parser = new PDFParser(new RandomAccessFile(f, "r"));
    parser.parse();
    PDDocument document = null;
    try (PrintWriter pw = new PrintWriter(txtFile);
            COSDocument cosDoc = parser.getDocument()) {
        document = new PDDocument(cosDoc);
        PDFTextStripper pdfStripper = new PDFTextStripper();
        parsedText = pdfStripper.getText(document);
        pw.print(parsedText);
    } catch (IOException e) {
        log.error(e.getMessage());
        e.printStackTrace();
    } finally {
        document.close();
        document = null;
    }
}
  • 1
    Glad to hear that, but you should also use PDDocument.load(), this would allow you to use the try-with-resource syntax => shorter, easier to understand code. – Tilman Hausherr Jul 18 '19 at 09:56
  • Yes, it is clear decision, but it not work, why i don't understand... Maybe problem in project properties... I don't understand :) – Filipp Berzenin Jul 18 '19 at 12:06
  • Maybe you must set the java source version in some setting. In Netbeans, it is in "Sources" after right-click on the project and choosing "Properties". If you're using another IDE, try a google search like "eclipse set java source version". If you don't find it, create a new question that includes the name of your IDE. Another possible causes might be that you have several java versions installed. You usually won't need that. – Tilman Hausherr Jul 18 '19 at 12:30