Skip to content

Instantly share code, notes, and snippets.

@ramonrails
Last active February 24, 2024 12:25
Show Gist options
  • Save ramonrails/2428c6148c7cfa9ca0b4843e4d67ed58 to your computer and use it in GitHub Desktop.
Save ramonrails/2428c6148c7cfa9ca0b4843e4d67ed58 to your computer and use it in GitHub Desktop.
Compressing a PDF using Ghostscript on command line
# utility functions
#
# compress PDF using ghostscript
#
# https://ghostscript.readthedocs.io/en/latest/VectorDevices.html#controls-and-features-specific-to-postscript-and-pdf-input
#
# -dPDFSETTINGS=/screen lower quality, smaller size. (72 dpi)
# -dPDFSETTINGS=/ebook for better quality, but slightly larger pdfs. (150 dpi)
# -dPDFSETTINGS=/prepress output similar to Acrobat Distiller "Prepress Optimized" setting (300 dpi)
# -dPDFSETTINGS=/printer selects output similar to the Acrobat Distiller "Print Optimized" setting (300 dpi)
# -dPDFSETTINGS=/default selects output intended to be useful across a wide variety of uses,
# possibly at the expense of a larger output file
#
# Usage: pdf-compress sm|md|lg /path/to/input.pdf /path/to/output.pdf
#
function pdf-compress {
# Check for required arguments
if [ $# -lt 2 ]; then
echo "Usage: pdf-compress sm|md|lg input.pdf [output.pdf | input-<size>.pdf]"
return 1
fi
# Validate size argument
if [[ ! "$1" =~ ^(sm|md|lg)$ ]]; then # Improved pattern for exact match
echo "Please use sm, md, or lg. *$1* is not a valid size."
echo "Usage: pdf-compress sm|md|lg input.pdf [output.pdf]"
return 1
fi
# Determine size based on argument
# default = medium size compress
size="ebook"
# check which size we need
case "$1" in
"sm") size="screen" ;;
"md") size="ebook" ;;
"lg") size="prepress" ;;
esac
# Check if gs command exists
if ! command -v gs &>/dev/null; then
echo "Error: Ghostscript (gs) is required. Please install it."
return 1
fi
# Construct output filename
if [ $# -eq 3 ]; then
filename="$3"
else
# Efficiently create "input-size.pdf" format
filename="${2%.*}-${size}.pdf"
fi
# Execute compression using gs
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS="/$size" \
-dNOPAUSE -dQUIET -dBATCH -sOutputFile="$filename" "$2"
# Optional: Open the compressed PDF (comment out if not needed)
open -R "$filename"
# Optional: show success message
# echo "PDF compressed successfully: $filename"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment