Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Created September 8, 2017 13:44
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cereal-s/06daa33ab239087d00b7b0766738fede to your computer and use it in GitHub Desktop.
Save cereal-s/06daa33ab239087d00b7b0766738fede to your computer and use it in GitHub Desktop.
Get number of pages from a PDF, using GhostScript.
<?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;
}
@hradhouani
Copy link

hradhouani commented Aug 10, 2021

it did not work without -dNOSAFER

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment