Skip to content

Instantly share code, notes, and snippets.

@ram-ai-kumar
Last active February 24, 2024 12:25
Show Gist options
  • Select an option

  • Save ram-ai-kumar/2428c6148c7cfa9ca0b4843e4d67ed58 to your computer and use it in GitHub Desktop.

Select an option

Save ram-ai-kumar/2428c6148c7cfa9ca0b4843e4d67ed58 to your computer and use it in GitHub Desktop.
Compressing a PDF using Ghostscript on command line
```bash
# 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 {
if [ $# -lt 3 ]; then
echo "Usage: compress-pdf sm|md|lg input.pdf output.pdf"
else
# default = medium size compress
size="ebook"
# check which size we need
case "$1" in
"sm") size="screen" ;;
"md") size="ebook" ;;
"lg") size="prepress" ;;
esac
# execute only if gs command exists in shell
if which gs &>/dev/null; then
$(which gs) -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/"$size" \
-dNOPAUSE -dQUIET -dBATCH -sOutputFile="$3" "$2"
# open the folder
open -R "$3"
else
echo "Note: Please install Ghostscript -- brew install ghostscript"
fi
fi
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment