Get the number of pages in a PDF document

Get the number of pages in a PDF document

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Get the number of pages in a PDF document

Determining the page count of a PDF file seems trivial, but it is notoriously difficult to implement reliably. In high-volume environments like graphic printing or reproduction companies, where documents originate from disparate sources using varying compression methods and generation tools, accuracy is non-negotiable. A solution that returns 1 for every document, regardless of actual content, renders the workflow useless before processing even begins.

Many developers initially reach for standard imaging libraries or high-level PDF parsers, only to hit performance walls or compatibility errors. The challenge lies in parsing binary streams and compressed objects correctly without assuming a specific generation tool.

Why Imagick fails

A common first step is attempting to use Imagick, the PHP extension built on top of ImageMagick. While powerful for raster image manipulation, it is fundamentally unsuited for this task. The extension often requires significant server configuration, including Apache restarts and library dependencies.

In practice, Imagick frequently returns 1 as the page count regardless of the document's actual length. Even when methods like getNumberImages() or identifyImage() are invoked, they fail to interpret PDF metadata correctly because they treat the file primarily as a collection of raster images rather than structured document objects. The processing time can also be prohibitive, sometimes taking several minutes per document. When accuracy and speed both suffer, relying on Imagick for PDF analysis is not a viable strategy.

The pitfalls of FPDI

Another popular option is FPDI (iText's FPDF & iText Document Import), which allows importing external PDFs into new ones. While easy to install via extraction or Composer, it relies on a free parser that has strict limitations regarding compression techniques.

If a document utilizes a compression method not supported by the parser—common in files from external clients—you will encounter a hard error: "FPDF error: This document... probably uses a compression technique which is not supported." Since many enterprise PDFs use advanced compression or specific encryption schemes, FPDI's free version often breaks on valid files, making it an unreliable choice for automated counting.

The regex trap

A tempting alternative is to open the file as a raw stream and search for metadata strings using regular expressions. A typical implementation might look like this:

$f = "test1.pdf";
$stream = fopen($f, "r");
$content = fread($stream, filesize($f));

if (!$stream || !$content) {
    return 0;
}

$count = 0;
// Attempting to match page count patterns
$regex = "/\/Count\s+(\d+)/";
$regex2 = "/\/Page\W*(\d+)/";
$regex3 = "/\/N\s+(\d+)/";

if (preg_match_all($regex, $content, $matches)) {
    $count = max($matches);
}

return $count;

This approach fails because PDFs are not simple text files. The /Count keyword often appears in contexts unrelated to page counts, such as arrays of font objects or color spaces. Similarly, searching for /N (Number) or generic /Page references yields inconsistent results. A regex-based parser cannot handle the binary structure, object cross-references, or compression algorithms inherent to the PDF format. It essentially guesses based on string patterns that are rarely standardized across different PDF creators.

The reliable approach: Counting Catalog Entries

To get an accurate count without assuming a specific generation tool or relying on heavy external binaries, you must parse the PDF structure directly. The most robust method involves reading the raw file content and counting the number of /Pages objects in the document's catalog tree.

PDFs are structured as a hierarchy of objects. Every page is defined within a Pages node, and this node contains an array of page references. By locating the root catalog object (usually marked by /Root) and traversing to its Pages child, you can count the direct children of that array.

The logic works as follows:

  1. Read the raw file content into a string.
  2. Locate the start of the PDF dictionary structure (often after the header %PDF-).
  3. Search for the /Root entry to find the catalog object.
  4. Navigate from the catalog to the Pages array.
  5. Count the number of items in that specific array.

This method bypasses compression issues because it operates on the raw stream data before decompression logic is applied by higher-level libraries. It does not rely on rendering images or embedding fonts, avoiding the performance penalties of Imagick. Furthermore, since it counts actual object references rather than guessing from keywords, it remains accurate even if the PDF creator uses non-standard metadata fields.

This technique requires careful handling of the raw stream to ensure you are counting the array entries correctly and ignoring references that might exist in other contexts. While slightly more complex to implement than a simple regex match, it is the only way to guarantee accuracy across a diverse mix of client-generated documents.

Our network