Skip to content

Instantly share code, notes, and snippets.

@huaminghuangtw
Created April 1, 2022 08:32
Show Gist options
  • Save huaminghuangtw/a4e375edbf717e250ffb8b2ec492ff15 to your computer and use it in GitHub Desktop.
Save huaminghuangtw/a4e375edbf717e250ffb8b2ec492ff15 to your computer and use it in GitHub Desktop.
Shell script to optimize a given pdf file on Linux
#!/bin/bash
#
# 1. Install ghostscript
# sudo apt-get update
# sudo apt-get install ghostscript
# 2. Use this shell script to optimize the given pdf
# sh optpdf.sh <filename>.pdf
file="$1"
filebase="$(basename "$file" .pdf)"
optfile="./${filebase}_opt.pdf"
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.5 -dNOPAUSE -dQUIET -dBATCH -dPrinted=false -sOutputFile="${optfile}" "${file}"
if [ $? -eq '0' ]; then
optsize=$(stat -c "%s" "${optfile}")
orgsize=$(stat -c "%s" "${file}")
if [ "${optsize}" -eq 0 ]; then
echo "No output! Keeping original file."
rm -f "${optfile}"
exit;
fi
if [ ${optsize} -ge ${orgsize} ]; then
echo "Didn't make it smaller! Keeping original file."
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