Skip to content

Instantly share code, notes, and snippets.

@tommyjtl
Created January 26, 2024 17:48
Show Gist options
  • Save tommyjtl/016b519f8bd710fbba4d8aa03c2dddce to your computer and use it in GitHub Desktop.
Save tommyjtl/016b519f8bd710fbba4d8aa03c2dddce to your computer and use it in GitHub Desktop.
PDF compression CLI with Ghostscript.
pdf-compress() {
QUALITY=150
INPUT_PDF=""
GS_BIN=$(command -v gs)
print_usage() {
echo "Usage: pdf-compress [-q|--quality <res>] <file>"
echo " Where:"
echo " -q|--quality <res> is the resolution for the PDF (default: 150)"
echo " <file> is the PDF file to compress"
}
if [ -z "$GS_BIN" ]; then
echo "Please make sure Ghostscript (gs command) is installed and available in PATH."
return 1
fi
while [ "$1" != "" ]; do
case $1 in
-h | --help)
print_usage
return 0
;;
-q | --quality)
shift
if [[ $1 =~ ^[0-9]+$ ]] ; then
if [ "$1" -gt 300 ] || [ "$1" -lt 50 ]; then
echo "Invalid quality: $1. Quality should be between 50 and 300."
return 1
else
QUALITY=$1
fi
else
echo "Invalid quality: $1. Quality should be a number."
return 1
fi
;;
*)
INPUT_PDF=$1
;;
esac
shift
done
if [ -z "$INPUT_PDF" ]; then
echo "Please specify the PDF file to compress."
print_usage
return 1
elif [ ! -f "$INPUT_PDF" ]; then
echo "File $INPUT_PDF does not exist."
return 1
fi
GS_ARGS="-sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -dColorImageResolution=$QUALITY -dGrayImageResolution=$QUALITY -dMonoImageResolution=$QUALITY -sOutputFile=output.pdf"
$GS_BIN $GS_ARGS "$INPUT_PDF"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment