How to get the PDF page count only with JavaScript

Get PDF page count from javascript

I have been busy for a while and could not dedicate much time into my blog. But here I am back with a ‘big bang’ post :)

This time I have created a javascript library for detecting the number of pages from a PDF document. This library is a kind of subset of PDF.js library from Mozilla. But the full library of PDF.js is very heavy and in development stage.

I have separated out the code necessary only to detect the page count and minified it as much as possible (trust me, this took me a lot of time to create!). This JS library is only 119kb in size, very light weight and very simple to use.

I have tested this with many of the standard format PDFs and it works fine.

Download the demo file including the JS library

How to use this library:

  • Include the PDFPageCount.js library into your target page
  • Call the function in the format

PDFPageCount.getPageCount(<target PDF file>,<callback function>);


PDFPageCount.getPageCount("HTML5_draft.pdf", callbackFunc);

  • Once the page count is detected the callback function will get the page count as a return parameter


Some Important Points:

  • The demo will work only from a webserver or from your localhost as PDF file cannot be loaded locally using modern browsers (due to file:/// load restrictions)
  • This library uses XMLHttpRequest (ajax) request to load the PDF. So the cross domain scripting security applies here (you can use the PDF files from the same domain by default). Additional details about this restriction can be referred here
  • This library is meant for modern browsers only
  • This software comes as-is with no warranty

If you are interested to be notified on my posts then you can use the subscribe option available on the right side bar.

Enjoy! I welcome your feedback and comments.


1 comment

  1. Juan says:

    Error at executing in a server (linux server). I beautified the code:

    Uncaught SyntaxError: Unexpected token = PDFPageCount.js:5311
    Uncaught ReferenceError: PDFPageCount is not defined

    without beautify: unexpected token: <

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>