Created
June 16, 2025 12:18
-
-
Save bdombro/43096b0814bb2d36d1d4b7dbb362befe to your computer and use it in GitHub Desktop.
pdf.sh - ghostscript shell commands to easy PDF compression
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pdf-compress() { | |
# Ensure ghostscript is installed | |
if ! command -v gs &> /dev/null; then | |
echo "Ghostscript is not installed. Please install it first." | |
return 1 | |
fi | |
# Check if the input file is provided | |
if [ -z "$1" ]; then | |
echo "Usage: pdf-compress <input.pdf>" | |
return 1 | |
fi | |
input_file="$1" | |
# Check if the input file exists | |
if [ ! -f "$input_file" ]; then | |
echo "File '$input_file' does not exist." | |
return 1 | |
fi | |
output_file="compressed_$input_file" | |
# Print size before | |
before_size=$(stat -c%s "$input_file" 2>/dev/null || stat -f%z "$input_file") | |
echo "Original size: $before_size bytes" | |
echo "Compressing '$input_file' to '$output_file'..." | |
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook \ | |
-dNOPAUSE -dQUIET -dBATCH -sOutputFile="$output_file" "$input_file" | |
# Print size after | |
after_size=$(stat -c%s "$output_file" 2>/dev/null || stat -f%z "$output_file") | |
echo "Compressed size: $after_size bytes" | |
# Move original to trash (Linux: gio, macOS: osascript) | |
if [[ "$(uname)" == "Darwin" ]]; then | |
# macOS: use AppleScript to move to trash | |
osascript -e 'tell application "Finder" to delete POSIX file "'"$input_file"'"' | |
else | |
# Linux: use gio | |
if command -v gio &> /dev/null; then | |
gio trash "$input_file" | |
else | |
echo "Warning: gio not found, cannot move to trash. Deleting file instead." | |
rm "$input_file" | |
fi | |
fi | |
# Rename compressed to original name | |
mv "$output_file" "$input_file" | |
echo "Compression complete: $input_file (was $before_size bytes, now $after_size bytes)" | |
} | |
pdf-compress-all() { | |
# Ensure ghostscript is installed | |
if ! command -v gs &> /dev/null; then | |
echo "Ghostscript is not installed. Please install it first." | |
return 1 | |
fi | |
# Check if there are any PDF files in the current directory | |
if ls *.pdf 1> /dev/null 2>&1; then | |
echo "Compressing all PDF files in the current directory..." | |
for f in *.pdf; do | |
pdf-compress "$f" | |
done | |
else | |
echo "No PDF files found in the current directory." | |
fi | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment