How do you convert PDFs to PNGs with ghostscript?

Sharad Goel picture Sharad Goel · Jun 4, 2011 · Viewed 9.5k times · Source

I'm usually able to use ghostscript to convert PDFs to PNGs with the command:

gs \
 -q \
 -dNOPAUSE \
 -dBATCH \
 -sDEVICE=pnggray \
 -g2550x3300 \
 -dPDFFitPage \
 -sOutputFile=output.png \
  input.pdf

But this doesn't work for some PDF files. For example, the command above converts this PDF file to this PNG -- the original PDF is just a small image in the lower left corner of the PNG, instead of filling the entire page.

Is there a more robust way to convert PDFs to PNGs with ghostscript, or perhaps some other command line tool?

Note: If I generate a new PDF file from the problematic one via "print -> save as pdf" in Preview on OS X, then the command works fine.

Answer

rlibby picture rlibby · Jun 4, 2011

Just use ImageMagick's convert.

convert foo.pdf foo.png

You can have more precise control over the page number with format strings, e.g.:

convert foo.pdf "foo-%03d.png"

And of course there are the myriad other ImageMagick options, but the basic command above is all you need most of the time.

Edit: about your "bad.pdf":

The short answer is to add the option -dUseCropBox to your gs command or -define pdf:use-cropbox=true to the convert command.

gs \
 -q \
 -dNOPAUSE \
 -dBATCH \
 -sDEVICE=pnggray \
 -g2550x3300 \
 -dPDFFitPage \
 -dUseCropBox \
 -sOutputFile=output.png \
  input.pdf

or

convert \
 -density 300 \
 -define pdf:use-cropbox=true \
  foo.pdf \
  foo.png

If you view the PDF in a text editor you can see that a CropBox and a MediaBox are specified, and that the CropBox is much smaller.