Skip to content

Instantly share code, notes, and snippets.

@okurka12
Last active January 26, 2026 01:12
Show Gist options
  • Select an option

  • Save okurka12/ad68752653498a76be153bcfbec7d423 to your computer and use it in GitHub Desktop.

Select an option

Save okurka12/ad68752653498a76be153bcfbec7d423 to your computer and use it in GitHub Desktop.
Changes DPI of a scanned PDF document using ghostscript
#!/bin/bash
# google gemini wrote this
# uses gostscript (sudo apt install ghostscript)
# 1. Check if the user provided all 3 arguments
if [ "$#" -ne 3 ]; then
echo "Usage: $0 <input_file> <output_file> <dpi>"
echo "Example: $0 input.pdf compressed.pdf 300"
exit 1
fi
INPUT_FILE="$1"
OUTPUT_FILE="$2"
TARGET_DPI="$3"
# 2. Check if the input file actually exists
if [ ! -f "$INPUT_FILE" ]; then
echo "Error: Input file '$INPUT_FILE' not found."
exit 1
fi
echo "Compressing '$INPUT_FILE' to ${TARGET_DPI} DPI..."
# 3. Run the Ghostscript command
gs \
-sDEVICE=pdfwrite \
-dCompatibilityLevel=1.4 \
-dNOPAUSE \
-dQUIET \
-dBATCH \
-dDownsampleColorImages=true \
-dColorImageResolution="$TARGET_DPI" \
-dDownsampleGrayImages=true \
-dGrayImageResolution="$TARGET_DPI" \
-dDownsampleMonoImages=true \
-dMonoImageResolution="$TARGET_DPI" \
-sOutputFile="$OUTPUT_FILE" \
"$INPUT_FILE"
# 4. Confirm success
if [ $? -eq 0 ]; then
OLDSIZE=$(wc -c "$INPUT_FILE" | cut -d " " -f 1)
OLDSIZEHUMAN=$(du -h "$INPUT_FILE" | cut -f 1)
NEWSIZE=$(wc -c "$OUTPUT_FILE" | cut -d " " -f 1)
NEWSIZEHUMAN=$(du -h "$OUTPUT_FILE" | cut -f 1)
RATIO=$(awk "BEGIN {printf \"%.2f\", 100 * $NEWSIZE / ($OLDSIZE + 0.001)}")
echo "Success! Saved to '$OUTPUT_FILE'."
echo "Old size: $OLDSIZEHUMAN"
echo "New size: $NEWSIZEHUMAN ($RATIO %)"
else
echo "Error: Something went wrong during compression."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment