Home > front end >  ImageMagick convert adds whitespace when converting PDF to PNG
ImageMagick convert adds whitespace when converting PDF to PNG

Time:03-11

I'm using ImageMagick to convert the following PDF to an PNG file.

enter image description here

but when converting with convert -density 300 -background white -alpha off -alpha remove file.pdf /tmp/file.png

the image gets a large white margin:

enter image description here

I do not want to trim the image afterwards, I just want ImageMagick to somehow respect the view-port or however that viewing information is being encoded in the PDF. Does anyone know which command-line parameter might enable this behavior?

Edit 10.03.2022: I'm using ImageMagick 7.1.0.16 with Ghostscript 9.55.0 inside an Alpine Linux docker image.

CodePudding user response:

I do not get your extra margin in ImageMagick 6.9.12-42 using Ghostscript 9.54. But changing the density does not seem to have any effect.

convert -density 300 -background white file.pdf[1] x2.png

enter image description here

The issues may be a malformed PDF. How was it created? Also what version of Ghostscript are you using? It could be a GS version issue.

If this was a scanned PDF that is a raster image in a vector PDF shell, then you could just use pdfimages to extract the raster files. See https://manpages.debian.org/testing/poppler-utils/pdfimages.1.en.html

CodePudding user response:

The hint from KenS was exactly what I was looking for - the PDF defines a CropBox that ImageMagick 7.1.0 was not using by default. The solution therefore is to modify the command to include the following -define information:

convert -define pdf:use-cropbox=true file.pdf /tmp/file.png 

Thank you all for your help!

  • Related