Convert every pdf in the current directory to png

If you have really strange names, ones that contain newlines or backslashes and the like, you could do something like this:

find . -type f -name '*.pdf' -print0 |
  while IFS= read -r -d '' file
    do convert -verbose -density 500 -resize 800 "${file}" "${file%.*}.png"
  done

That should be able to deal with just about anything you throw at it.

Tricks used:

  • find ... -print0 : causes find to print its results separated by the null character, let's us deal with newlines.
  • IFS= : this will disable word splitting, needed to deal with white space.
  • read -r: disables interpreting of backslash escape characters, to deal with files that contain backslashes.
  • read -d '': sets the record delimiter to the null character, to deal with find's output and correctly handle file names with newline characters.
  • ${file%.*}.png : uses the shell's inbuilt string manipulation abilities to remove the extension.

You can use bash for loop as follows:

#!/bin/bash
for pdfile in *.pdf ; do
  convert -verbose -density 500 -resize '800' "${pdfile}" "${pdfile%.*}".png
done

You could use mogrify to batch convert & resize all .pdfs in the current directory:

mogrify -verbose -density 500 -resize 800 -format png ./*.pdf

When using a different format (in this case -format png) the original .pdfs are left untouched, the output files having the same name except for the extension which will be changed to the one specified by format.