Skip to content

Instantly share code, notes, and snippets.

@slowkow
Last active August 18, 2023 22:13
Show Gist options
  • Save slowkow/c28d79d4a8199af9f23ec7f28f9ef55e to your computer and use it in GitHub Desktop.
Save slowkow/c28d79d4a8199af9f23ec7f28f9ef55e to your computer and use it in GitHub Desktop.
Optimize PDF files with Ghostscript.
#!/usr/bin/env bash
# pdfoptim.sh
#
# Optimize a PDF with Ghostscript
#
# Usage: bash pdfoptim.sh FILE.pdf
#
# This will copy the input file to FILE-original.pdf
# And write an optimized file to FILE.pdf
#
# Install dependencies: brew install ghostscript
#
# Learn more about Ghostscript options: https://ghostscript.com/docs/9.54.0/Use.htm
if [[ "$#" -ne 1 ]]; then
echo "usage: $0 in.pdf"
exit 1
fi
dpi=300
downsample=0.8
in_file="$1"
out_file="${TMPDIR}pdfoptim.$(uuidgen).pdf"
gs \
-o"${out_file}" \
-sDEVICE=pdfwrite \
-dDownsampleColorImages=true \
-dDownsampleGrayImages=true \
-dDownsampleMonoImages=true \
-dColorImageResolution=${dpi} \
-dGrayImageResolution=${dpi} \
-dMonoImageResolution=${dpi} \
-dColorImageDownsampleThreshold=${downsample} \
-dGrayImageDownsampleThreshold=${downsample} \
-dMonoImageDownsampleThreshold=${downsample} \
"${in_file}"
command mv -f "$in_file" "${in_file%.pdf}-original.pdf"
command mv -f "$out_file" "$in_file"
command rm -f "$out_file"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment