Created
September 8, 2017 13:44
-
-
Save cereal-s/06daa33ab239087d00b7b0766738fede to your computer and use it in GitHub Desktop.
Get number of pages from a PDF, using GhostScript.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Return the number of pages of a PDF. | |
* | |
* Imagick::pingImage() takes too much when dealing with big files. | |
* | |
* Command to execute: | |
* | |
* gs -q -dNODISPLAY -c "(%s) (r) file runpdfbegin pdfpagecount = quit" | |
* | |
* where %s is the filename. | |
* | |
*/ | |
try { | |
$r = ''; | |
$f = array_key_exists(1, $argv) ? trim($argv[1]) : NULL; | |
if( is_null($f) || ! file_exists($f)) | |
throw new Exception('File not found or not defined', 1); | |
exec(sprintf('gs -q -dNODISPLAY -c "(%s) (r) file runpdfbegin pdfpagecount = quit"', $f), $res, $ret); | |
if(0 <> $ret) | |
$r = 'Error ' . $ret; | |
else | |
$r = (int) $res[0]; | |
} catch (Exception $e) { | |
$r = sprintf('Error (%u) %s at line %u', $e->getCode(), $e->getMessage(), $e->getLine()); | |
$r .= PHP_EOL; | |
$r .= 'Usage: ' . basename(__FILE__) . ' file.pdf'; | |
} finally { | |
print $r . PHP_EOL; | |
} |
it did not work without -dNOSAFER
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello,
your request is a bit vague, can you be more specific? The above script is for command-line usage:
this will print the number of pages as int or an error as string. What can be useful for you is:
And execute as:
But, I would suggest to do NOT include this into a product page, because you don't want to execute this at each page load, it will hit the CPU heavily. Run it when the PDF is submitted and/or modified, then save the result into a database and display that when the product page is loaded.
Bye.