简体   繁体   中英

Count pages in PDF file using Imagemagick - PHP

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

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

我用解决了

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM