Skip to content

Instantly share code, notes, and snippets.

@mozurin
Created January 5, 2021 04:11
Show Gist options
  • Save mozurin/6025cc0e77df0b836e4ba934577569be to your computer and use it in GitHub Desktop.
Save mozurin/6025cc0e77df0b836e4ba934577569be to your computer and use it in GitHub Desktop.
Rasterize PDF files with Ghostscript and ImageMagick.
#!/bin/sh
# Rasterize PDF files with Ghostscript and ImageMagick.
set -e
# parse options
DENSITY='600'
ADDEXT='.raster'
while getopts d:e: O; do
case $O in
'd' ) DENSITY=$OPTARG;;
'e' ) ADDEXT=$OPTARG;;
esac
done
shift $((OPTIND-1))
# convert all specified files
if [ $# -le 0 ]; then
echo 'Target filename argument is required.' >&2
exit
fi
TMPDIR=$(mktemp -d)
trap "rm -rf $TMPDIR" EXIT
for file in "$@"; do
gs -dNOPAUSE -r$DENSITY -dBATCH -sDEVICE=png16m \
-sOutputFile="$TMPDIR/tmp-%02d.png" "$file"
# remove profile to avoid 'Insufficient data for an image' error
convert "$TMPDIR"/tmp-*.png +profile '*' "${file%.*}$ADDEXT.pdf"
rm "$TMPDIR"/tmp-*.png
done
@arampak
Copy link

arampak commented Feb 28, 2022

Ghostscript has the PDF image option (see https://www.ghostscript.com/doc/current/Devices.htm) that allows to convert PDF to raster without need of a second step, and even with option to chose the final format in PDF and the color depth.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment