Search code examples
javaspring-bootfileloadingpdfbox

PDFBox | Crash on line: PDDocument.load(file)


I have the following simplified code:

PDFTextStripper pdfStripper = new PDFTextStripper();
PDDocument doc;
String text = "";

try {
    File textFile = new File("C:/Users/user/Desktop/PDF-test.txt");
    doc = PDDocument.load(textFile);
    text = pdfStripper.getText(doc);
} finally {
   ...
}

...

PDPageContentStream content = new PDPageContentStream(doc, page);

content.setFont(font, 12);

content.beginText();
// Write to page using a text file
content.showText(text);
content.endText();
content.close();

The Problem

I get the following error: java.io.IOException: Error: End-of-File, expected line on the line:

doc = PDDocument.load(textFile); in the try block.


What I've Tried

I've tried these solutions but none have worked:


Expected Results

I want to load the text file without error and display it as a PDF with PDFBox.


Solution

  • PDDocument.load expects a pdf file, not a txt file.

    See javadoc of PDDocument: https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/PDDocument.html#load(java.io.File)