10
Sep 11PHP & Ghostscript – Count pages of PDF
Count pages of a pdf is pretty simple!
One way of finding out how to count the pages of a PDF file with PHP apart from imagemagick which always performance very slow and shaky (depends on the version) is to use the Linux Ghostscript library via shell and PHPs exec() commands.
//$pdf full path to pdf file
function countPages($pdf = null)
{
if($pdf !== null)
{
$c = "gs " . @escapeshellcmd("-q -sPDFname=".$pdf." ".rtrim(dirname(__FILE__), "/")."/counter.ps");
@exec($c, $r);
if(stristr($r[0], "error") === false)
{
if((bool)preg_match("/\%\%Pages\:\s+([0-9]{1,})/i", $r[0], $m))
{
return (int)$m[1];
}
}else{
throw new Exception($r[0]);
}
}
}
Just make sure Ghostscript is installed and configured right and executable from bash and you have the counter.ps postscript file in the same directory from where you call the script. The content of the .ps file looks like. I found it on some other page but cannot remember where exactly so credits to unknown:
% pdfpagecount.ps
% read pdf file and output number of pages
% based on pdf2dsc.ps with one line taken from ps2ascii.ps
/PDFfile PDFname (r) file def
/PageCountString 255 string
def
systemdict /.setsafe known { .setsafe } if
/.show.stdout { (%stdout) (w) file } bind def
/puts { .show.stdout exch writestring } bind def
GS_PDF_ProcSet begin
pdfdict begin
PDFfile
pdfopen begin
/FirstPage where { pop } { /FirstPage 1 def } ifelse
/LastPage where { pop } { /LastPage pdfpagecount def } ifelse
(%%Pages: ) puts
LastPage FirstPage sub 1 add
PageCountString cvs puts
quit
Just parse the result with regular expressions for the line with “Pages” and you have the number of pages of your PDF file. I have tried it with different PDF version and standards and so far the results have been all correct.