Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page count of Pdf with Java

Tags:

java

pdf

size

itext

at the moment I am using itext to read the page count of a pdf. This takes quite long because the lib seems to scan the whole file.

Is the page information somewhere in the header of the pdf, or is a full filescan needed?

like image 864
hans sausage Avatar asked May 17 '11 06:05

hans sausage


2 Answers

That's correct. iText parses quite a bit of a PDF when it is opened (it doesn't read the contents of stream objects, but that's about it)...

UNLESS you use the PdfReader(RandomAccessFileOrArray) constructor, in which case it will only read the xrefs (mostly required), but not parse anything until you start requesting specific objects (directly or via various calls).

The first PDF program I ever wrote did exactly this. It opened up a PDF and doing the bare minimum amount of work necessary, read the number of pages. It didn't even parse the xrefs it didn't have to. Haven't thought about that program in years...

So while not perfectly efficient, it'll be vastly more efficient to use a RandomAccessFileOrArray:

int efficientPDFPageCount(String path) {
  RandomAccessFileOrArray file = new RandomAccessFileOrArray(path, false, true );
  PdfReader reader = new PdfReader(file);
  int ret = reader.getNumberOfPages();
  reader.close();
  return ret;
}

Update:

The itext API underwent a little overhaul. Now (in version 5.4.x) the correct way to use it is to pass through java.io.RandomAccessFile:

int efficientPDFPageCount(File file) {
     RandomAccessFile raf = new RandomAccessFile(file, "r");
     RandomAccessFileOrArray pdfFile = new RandomAccessFileOrArray(
          new RandomAccessSourceFactory().createSource(raf));
     PdfReader reader = new PdfReader(pdfFile, new byte[0]);
     int pages = reader.getNumberOfPages();
     reader.close();
     return pages;
  }
like image 54
Mark Storer Avatar answered Sep 20 '22 21:09

Mark Storer


Lars Vogel uses the following code:

PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();

I'd be surprised if the implementation of getNumberOfPages is slower than any other solution.


Section F.3.3 says there is a header-field called N described as follows:

N     integer (Required)      The number of pages in the document.
like image 41
aioobe Avatar answered Sep 22 '22 21:09

aioobe