How to get the number of pages in a PDF document using PHP ?

PHP offers inbuilt functions and extensions that can be used to count the number of pages in a document with .pdf extension. There are numerous ways by which this can be done. Following are the methods used to count the pages in a pdf document:

Method 1: Using ImageMagic extension: The extension offered by PHP is ImageMagic which is able to understand the pdf document. The command used for the same is “identify” command. So the complete PHP function dedicated to the required purpose is Imagick::identifyImage().

Method 2: Using TCPDI function: Another way to do this is by using the TCPDI function. It does not use any PHP library for performing this task. The following line of code can be used.

$pageCount = (new TCPDI())->setSourceData((string)file_get_contents($fileName));

Method 3: Using pdfinfo: For Linux users, there is a faster way to count the number of pages in a pdf document than “identity” function. The command given below can be used for the same. Before executing this command, pdfinfo needs to be installed. This command works very fast when the number of pages in the pdf document is too large. For Windows users, the pdfinfo is available as pdfinfo.exe. Here is the command:



exec(‘/usr/bin/pdfinfo ‘.$tmpfname.’ | awk \’/Pages/ {print $2}\”, $output);

Method 4: Using pdf as text file: Now, let us see the code in PHP which will tell us the number of pages in a pdf document. In this code, we have created a function “count” containing the logic. Also, in the variable “path”, the path of the pdf whose number of pages are to be counted is written. Make sure, you write the path correctly.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
$path = 'pdf/GFG.pdf';
$totalPages = count($path);
    
echo $totoalPages;
    
function count($path) {
  $pdf = file_get_contents($path);
  $number = preg_match_all("/\/Page\W/", $pdf, $dummy);
  return $number;
}  
?>

chevron_right


Output:

4
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.