Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking Ghostscript from PHP: Unable to open the initial device

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.

like image 623
alexantd Avatar asked May 10 '26 16:05

alexantd


2 Answers

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.

like image 119
profitphp Avatar answered May 13 '26 08:05

profitphp


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.

like image 32
nilli Avatar answered May 13 '26 07:05

nilli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!