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;
}
@Asenar
Copy link

Asenar commented Dec 16, 2019

Thanks for sharing this !

@BroadbandInternet
Copy link

Kindly advise where to insert this to show count in product page ?

@cereal-s
Copy link
Author

cereal-s commented Jan 23, 2021

Kindly advise where to insert this to show count in product page ?

Hello,
your request is a bit vague, can you be more specific? The above script is for command-line usage:

php ping.gs.php a.pdf

this will print the number of pages as int or an error as string. What can be useful for you is:

function pingPDF($file) {
    exec(sprintf('gs -q -dNODISPLAY -c "(%s) (r) file runpdfbegin pdfpagecount = quit"', $file), $res, $ret);

    if(0 == $ret) {
        return (int) $res[0];
    }

    return 0;
}

And execute as:

echo function('a.pdf');

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.

@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