开发者

Invoking Ghostscript from PHP: Unable to open the initial device

I have installed Ghostscript from MacPor开发者_开发问答ts, 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.


I encountered the **** Unable to open the initial device, quitting. error message when using PHP to call a pdf generation script.

I was following the path of permissions and options, and stumbled upon something entirely by accident. I wasn't assigning enough memory to PHP to complete the transaction.

I added:

ini_set("memory_limit", "2048M");

prior to invoking my generation script and it completed without error. Memory obviously might be excessive, but you can adjust as required.


I solved the problem by removing the double quotes in thе line:

$cmd = '/opt/local/bin/gs -sDEVICE=pdfwrite -dNOPAUSE \
-dBATCH -dSAFER -dFirstPage=20 -dLastPage=20
-sOutputFile=%stdout  /path/to/input/pdf.pdf';

Tested with shell_exec on PHP+Ubuntu18.4+Apache2.4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜