Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

number of pages in a pdf file

Tags:

php

pdf

Does anyone know how I can count the number of pages in a pdf file using php? Thanks!

like image 615
Julie Avatar asked Jul 08 '09 13:07

Julie


2 Answers

Based on R Ubben's answer I found the following PHP code to give good results:

function count_pages($pdfname) {
  $pdftext = file_get_contents($pdfname);
  $num = preg_match_all("/\/Page\W/", $pdftext, $dummy);
  return $num;
}

\W matches any non-alphanumeric character and excludes things like /Pages, /PageMode etc.

like image 156
fuenfundachtzig Avatar answered Oct 22 '22 05:10

fuenfundachtzig


PDFs store pages in a tree. "/Pages" objects can have a "/Parent" and "/Kids" entries, followed by a "/Count". You can't sum the "/Count" entries because a Kid might be another Pages node. The "/Page" object is the leaf.

Open the pdf as a text file and count the number of times "/Page" (not "/Pages") appears in the file. That should be correct most of the time.

like image 29
R Ubben Avatar answered Oct 22 '22 05:10

R Ubben