Count pages in PDF file using Imagemagick - PHP

那年仲夏 提交于 2019-12-05 08:06:38

Instead of using "identify -format %n $file"(which can turn out to be extremely slow for complex or for mult-page PDFs) you should rather use the right tool for the job, pdfinfo:

exec("pdfinfo $file | grep Pages: | awk '{print $2}'")

which is faster by several magnitudes...

I solved it using;

exec("identify -format %n $file")

From the mentioned page, here is a sample code to get the page count:

<?php
public function getNumPagesInPDF(array $arguments = array())
{
@list($PDFPath) = $arguments;
$stream = @fopen($PDFPath, "r");
$PDFContent = @fread ($stream, filesize($PDFPath));
if(!$stream || !$PDFContent)
    return false;
$firstValue = 0;
$secondValue = 0;
if(preg_match("/\/N\s+([0-9]+)/", $PDFContent, $matches)) {
    $firstValue = $matches[1];
}
if(preg_match_all("/\/Count\s+([0-9]+)/s", $PDFContent, $matches))
{
    $secondValue = max($matches[1]);
}
return (($secondValue != 0) ? $secondValue : max($firstValue, $secondValue));
}
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!