Skip to content

Instantly share code, notes, and snippets.

@ildyria
Created May 21, 2019 21:34
Show Gist options
  • Save ildyria/b3a3f0d8614397f9fae8cebb0b207e66 to your computer and use it in GitHub Desktop.
Save ildyria/b3a3f0d8614397f9fae8cebb0b207e66 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# optpdf file.pdf
# This script will attempt to optimize the given pdf
file="$1"
filebase="$(basename "$file" .pdf)"
optfile="/tmp/$$-${filebase}_opt.pdf"
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${optfile}" "${file}"
# -dPDFSETTINGS=/screen (screen-view-only quality, 72 dpi images)
# -dPDFSETTINGS=/ebook (low quality, 150 dpi images)
# -dPDFSETTINGS=/printer (high quality, 300 dpi images)
# -dPDFSETTINGS=/prepress (high quality, color preserving, 300 dpi imgs)
# -dPDFSETTINGS=/default (almost identical to /screen)
if [ $? == '0' ]; then
optsize=$(stat -c "%s" "${optfile}")
orgsize=$(stat -c "%s" "${file}")
if [ "${optsize}" -eq 0 ]; then
echo "No output! Keeping original"
rm -f "${optfile}"
exit;
fi
if [ ${optsize} -ge ${orgsize} ]; then
echo "Didn't make it smaller! Keeping original"
rm -f "${optfile}"
exit;
fi
bytesSaved=$(expr $orgsize - $optsize)
percent=$(expr $optsize '*' 100 / $orgsize)
echo Saving $bytesSaved bytes \(now ${percent}% of old\)
rm "${file}"
mv "${optfile}" "${file}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment