
pagecount is a small open-source program that prints the number of pages in a PDF. When it cannot be sure of the number, it refuses and exits with code 2. The point is to check what the document says about itself instead of taking a library’s answer on trust.
A PDF’s pages are the leaves of a tree. The trailer names the catalog, the catalog names the root /Pages node, each /Pages node lists its children in /Kids, and the leaves whose /Type is /Page are the pages. The root also carries a /Count, the total the writer claims. pagecount walks the tree and compares the two. It never searches the file for the bytes /Type /Page, which would count a page mentioned inside a string.
A file whose /Count says 7 and whose tree holds 3 pages is inconsistent, and a program that prints either number is guessing. pagecount prints the error with both numbers. It refuses in the same way for an encrypted file, a missing startxref, a broken cross-reference entry, or a page tree with a cycle.
The full list of refusals, the test against pdfinfo on 200 court filings, downloads and source are on the pagecount tool page.
peter@docs2info.com