Reading pdf with iText

I am having a problem reading pdf files using iText in java. I can only read one page, but when I go to the second page, it gives an exception. I want to read all the pages of any PDF file.

PdfTextExtractor parser =new PdfTextExtractor(new PdfReader("C:/Text.pdf")); parser.getTextFromPage(3); 

I use these lines, and the second line is an exception.

+6
java itext
source share
4 answers
  • Try changing the location of the file. Sometimes the OS does not allow you to read files from some system disks by other applications. Put somewhere in D: etc. I encounter this problem in Vista when reading files from the desktop.

  • I actually used the same two lines of code in one of my PDF files, and it printed the text. Also make sure you have enough pages in the PDF. (3 pages or more) or try using parser.getTextFromPage (1) etc. to get content from other pages.

+2
source share

when you say one page, do you mean the first page? can you index pages incorrectly? Without additional information, it could be anything.

0
source share

Do you rebuild the parser and reader for each operation? You can do this, but it is not very efficient (there is a lot of overhead when creating a new PdfReader).

0
source share
 import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.PdfTextExtractor; /** * This class is used to read an existing * pdf file using iText jar. * @author javawithease */ public class PDFReadExample { public static void main(String args[]){ try { //Create PdfReader instance. PdfReader pdfReader = new PdfReader("D:\\testFile.pdf"); //Get the number of pages in pdf. int pages = pdfReader.getNumberOfPages(); //Iterate the pdf through pages. for(int i=1; i<=pages; i++) { //Extract the page content using PdfTextExtractor. String pageContent = PdfTextExtractor.getTextFromPage(pdfReader, i); //Print the page content on console. System.out.println("Content on Page " + i + ": " + pageContent); } //Close the PdfReader. pdfReader.close(); } catch (Exception e) { e.printStackTrace(); } } } 
0
source share

All Articles