Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 743
user319080 Avatar asked Apr 17 '10 06:04

user319080


2 Answers

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.

like image 50
sanchez Avatar answered Oct 13 '22 12:10

sanchez


There are various options to control which "media size" Ghostscript renders a given input:

-dPDFFitPage
-dUseTrimBox
-dUseCropBox

With PDFFitPage Ghostscript will render to the current page device size (usually the default page size). With UseTrimBox it will use the TrimBox (and it will at the same time set the PageSize to that value). With UseCropBox it will use the CropBox (and it will at the same time set the PageSize to that value). By default (give no parameter), Ghostscript will render using the MediaBox.

For your example, it looks like adding "-dUseCropBox" will do the job you're expecting.

Note, you can additionally control the overall size of your output by using "-sPAPERSIZE" (select amongst all pre-defined values Ghostscript knows) or (for more flexibility) use "-dDEVICEWIDTHPOINTS=NNN -dDEVICEHEIGHTPOINTS=NNN".

like image 32
5 revs Avatar answered Oct 13 '22 12:10

5 revs