1

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.

Compiler v2
  • 3,509
  • 10
  • 31
  • 55
  • 1
    What do you want to do? PDDocument.load expects a pdf file, not a txt file. See javadoc https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/PDDocument.html#load(java.io.File) – TomStroemer May 06 '20 at 19:29
  • @TomStroemer Well well, thanks for that. I was under the assumption that it could load text files. Fixing now... – Compiler v2 May 06 '20 at 19:31
  • @TomStroemer It worked! Thank you! Please add that as an answer to my question and I will give you the rep. – Compiler v2 May 06 '20 at 19:34

2 Answers2

3

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)

TomStroemer
  • 1,390
  • 8
  • 28
  • Thank you for your quick answer and time. Have yourself a good day! – Compiler v2 May 06 '20 at 19:39
  • Hi @TomStroemer, I am using `pdf` file, not text file I'm getting this type exception. system can't execute this line `PDDocument.load(file)` My code: `String pdfDir = tempPdfDir + File.separatorChar + "mypdf.pdf" File file = new File("${pdfDir}") pd = PDDocument.load(file) // this line can't execute.` error: `java.io.IOException: Error: End-of-File, expected line` – Asif Mar 10 '21 at 10:36
  • Use new File(pdfDir) instead of new File("${pdfDir}"). Check if the File exists, before you call the function. (file.exists()). Please create a separate issue if you still have problems. – TomStroemer Mar 10 '21 at 14:41
0

In PDFBox 3.0, you have to use org.apache.pdfbox.Loader.loadPDF(new File(...))

For more information, check https://pdfbox.apache.org/3.0/migration.html

Tuhin Paul
  • 558
  • 4
  • 11