How to Count the Pages in a PDF File with PHP
PHP provides a range of extensions and functions for getting the number of pages in a PDF document.
Here, we will check out the different methods used for that purpose.
Applying the ImageMagic Extension
The ImageMagic extension of PHP is capable of understanding a pdf document. The used command is identify. In other words, the complete PHP function for counting the number of pages in a PDF document is Imagick::identifyImage().
Applying the TCPDI Function
An alternative method is using the TCPDI function. No library is used by it for carrying out the task.
So, the code to use is shown below:
<?php
$pageCount = (new TCPDI())->setSourceData((string) file_get_contents($fileName));
?>
Applying pdfinfo
A faster method to use for Linux users is pdfinfo. It counts the number of pages in a PDF file quite fast.
But, note that before running the command, you should install pdfinfo.
For Windows, it is available as pdfinfo.exe.
The command to use looks as follows:
exec('/usr/bin/pdfinfo '.$tmpfname.' | awk \'/Pages/ {print $2}\", $output);
Applying pdf as a Text File
In this section, you will see the PHP code that gets the number of pages in a PDF document.
Within the code, a function count is created that contains the logic.
Within the path variable, the path of the pdf, whose page numbers should be counted, is written.
It is essential to write the correct path.
Here is an example:
<?php
$path = 'pdf/GFG.pdf';
$totalPages = count($path);
echo $totalPages;
function count($path)
{
$pdf = file_get_contents($path);
$number = preg_match_all("/\/Page\W/", $pdf, $dummy);
return $number;
}
?>
4