Search code examples
stdoutstderrghostscript

Prevent Ghostscript from writing errors to standard output


I'm using Ghostscript to rasterize the first page of a PDF file to JPEG. To avoid creating tempfiles, the PDF data is piped into Ghoscripts's stdin and the JPEG is "drained" on stdout. This pipeline works like a charm until GS receives invalid PDF data: Instead of reporting all error messages on stderr as I would have expected, it still writes some of the messages to stdout instead.

To reproduce:

$ echo "Not a PDF" >test.txt
$ /usr/bin/gs -q -sDEVICE=jpeg -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=1 \
    -r300 -sOutputFile=- - < test.txt 2>/dev/null
Error: /undefined in Not
Operand stack:

Execution stack:
...

Note the 2>/dev/null above does not suppress the error messages. Ghostscript's documentation already warned that writing to stdout requires the -q flag to suppress messages on stdout, but I still seem to be missing something here.


Solution

  • If you want to really silence Ghostscript, modify your command line like this:

    /usr/bin/gs -q        \
         -sstdout=%stderr \
         -sDEVICE=jpeg    \
         -dBATCH          \
         -dNOPAUSE        \
         -dLastPage=1     \
         -r300            \
         -sOutputFile=-   \
         - < test.txt 2>/dev/null
    

    The addition of -sstdout=%stderr allows Postscript stdout to be redirected, while still allowing drivers to write to stdout. (That patch is in Ghostscript since ~2001, Sept 22.)