I have installed Ghostscript from MacPorts, and am trying to invoke it from a PHP script to extract single page from a multi-page PDF file and then output it. My code looks like this:
<?php
$cmd = '/opt/local/bin/gs -sDEVICE=pdfwrite -dNOPAUSE \
-dBATCH -dSAFER -dFirstPage=20 -dLastPage=20
-sOutputFile=%stdout "/path/to/input/pdf.pdf"';
// Will uncomment this when it works
// header("Content-Type: application/pdf");
putenv("GS_LIB=/opt/local/share/ghostscript/9.02/lib");
putenv("GS_FONTPATH=/opt/local/share/ghostscript/fonts");
putenv("TMPDIR=/tmp");
passthru($cmd);
When I hit this script in a web browser, I see:
GPL Ghostscript 9.02 (2011-03-30) Copyright (C) 2010 Artifex Software, Inc.
All rights reserved. This software comes with NO WARRANTY: see the file
PUBLIC for details. **** Unable to open the initial device, quitting.
The same command works from a shell.
The apache/webserver user likely does not have the permissions or the same environment variables. Perhaps try sudo, or make sure apache has proper permissions.
I had this error too, and it took me 5 hours to figure out what the solution to it was. Notice the difference between these two code blocks:
$cmd = '/opt/local/bin/gs -sDEVICE=pdfwrite -dNOPAUSE \
-dBATCH -dSAFER -dFirstPage=20 -dLastPage=20
-sOutputFile=%stdout "/path/to/input/pdf.pdf"';
$cmd = '/opt/local/bin/gs -sDEVICE=pdfwrite -dNOPAUSE \
-dBATCH -dSAFER -dFirstPage=20 -dLastPage=20 \
-sOutputFile=%stdout "/path/to/input/pdf.pdf"';
The shell doesn't appreciate the unexpected linebreaks, so by just adding a backslash \ in front of every newline, the problem is solved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With