Tuesday 18 May 2010

Convert PDF to PNG Using ImageMagick

Here is a short bash script that will try to convert all images in your folder into PNGs. The tricky bit is actually to specify the right options when running convert in order to achieve a decent quality.

Here's the code:

for file in *.pdf; do \
echo $file;\
convert -density 600x600 -resize 800x560 -quality 90 $file `echo $file|cut -f1 -d'.'`.png;\
done

The important bit is density, which specifies the resolution of the image in DPI. Resizing and setting a quality is optional, but allows you to tweak the resulting file size. Quality 90 means 90% quality in the case of PNGs and JPGs.

Note that you can run convert also from the command line to convert a single image:

convert -density 600x600 input.pdf output.pdf
convert -density 600x600 -resize 800x560 -quality 90 input.pdf output.pdf

Convert is part of the Linux package ImageMagic, which should be included in most distributions (Ubuntu, Debian, Mandrake, Red Hat etc...).