7

I am using PHP 5 with Apache in my Windows Vista PC. I have Imagemagick already installed and configured. I want to count the total number of pages in a pdf file using imagick.

I fount one solution here, but dont know how to open pdf file as text and count pages.

somebody give me a clear solution to count pages using imagemagick like

identify -format %n testfile.pdf

From googling, I found some workarounds or examples;

  1. imagick(identify -format %n testfile.pdf)
  2. identify -density 12 -format "%p" testfile.pdf
  3. identify -format %n testfile.pdf

I don't know how to make use of this stuff..

Community
  • 1
  • 1
Alfred
  • 21,058
  • 61
  • 167
  • 249

3 Answers3

14

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...

Kurt Pfeifle
  • 86,724
  • 23
  • 248
  • 345
  • Useful pointer, but I had some difficulty figuring out how to get pdfinfo in my systems. Finally: Debian/Ubuntu: sudo aptitude install poppler-utils; OSX: brew install poppler. – Giuseppe Oct 18 '14 at 08:04
3

I solved it using;

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

Alfred
  • 21,058
  • 61
  • 167
  • 249
  • 3
    This will be *extremely* slow for multi-page PDFs, especially for ones with more complex graphics on the pages... – Kurt Pfeifle Aug 13 '12 at 13:46
-1

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));
}
?>
jonjbar
  • 3,896
  • 1
  • 25
  • 46
  • this is not working for me.. :( I set $PDFPath = "test.pdf"; , but not working. What should I do? – Alfred Sep 18 '11 at 16:21
  • This thread might help you then: http://stackoverflow.com/questions/1143841/count-the-number-of-pages-in-a-pdf-in-only-php – jonjbar Sep 18 '11 at 16:21
  • This solution will work not in all cases. For me this script didn't work for PDF 1.6, but worked for 1.4 and 1.5 versions – gorodezkiy Jul 23 '15 at 19:46
  • the PDFlib library no longer maintained since 2010. But even worst, its commercial and not public domain. – Henry May 21 '18 at 10:58