Skip to content
Related Articles

Related Articles

How to get the number of pages in a PDF document using PHP ?
  • Last Updated : 29 Jul, 2020

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.




<?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;
}  
?>

Output:

4

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :