Obey the MediaBox/CropBox in PDF when using Ghostscript to render a PDF to a PNG

user319080 picture user319080 · Apr 17, 2010 · Viewed 7.3k times · Source

I've been using Ghostscript to convert my single figure plots rendered in PDF to PNG:

gswin32c -sDEVICE=png16m -r300x300 -sOutputFile=junk.png ^
         -dBATCH -dNOPAUSE Figure_001-a.pdf

This works in the sense I get a PNG out and it contains the plot.

But it contains a huge amount of white space as well (an example source image: http://cdsweb.cern.ch/record/1258681/files/Figure_001-a.pdf).

If you view it in Acrobat you'll note there is no white space around the plot. If you use the above command line you'll find the plot is only about 1/3 of the space.

When doing the same thing with an EPS file I run into the same problem. However, there is the command-line parameter -dEPSCrop that one can pass to get the PS rendering engine to pay attention to the BoundingBox.

I need the similar argument for rendering PDFs. I was not able to find it in docs (nor even the -dEPSCrop, actually).

Answer

sanchez picture sanchez · Jan 4, 2014

I had exactly the same issue. I fixed it by adding -dUseArtBox switch.

Example:

 /usr/bin/gs -dUseArtBox -dNOPAUSE -sDEVICE=pngalpha -sOutputFile=output.png input.pdf

Note: -dUseArtBox switch is supported since ghostscript version 9.07

-dUseArtBox Sets the page size to the ArtBox rather than the MediaBox. The art box defines the extent of the page's meaningful content (including potential white space) as intended by the page's creator. The art box is likely to be the smallest box. It can be useful when one wants to crop the page as much as possible without losing the content.