· Gists  · 4 min read

Get your PDFs compressed in a jiffy

Who needs to search "Compress PDF online for free"

Who needs to search "Compress PDF online for free"

Do you often find yourself needing to compress a PDF - maybe because you’re submitting a form to a system with file size limits, or you’re trying to send it via email?

Instead of searching “Compress PDF online for free”, you can do it locally using a simple shell function with Ghostscript:

Define a Bash Function

compresspdf() {
    echo 'Usage: compresspdf [input file] [output file] [screen|ebook|printer|prepress]'
    gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"screen"} \
    -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"
}

As seen in Super User.


Tip

his function uses Ghostscript, so make sure it’s installed.
On macOS, run: brew install ghostscript.

Example Usage

compresspdf "my-pdf-file.pdf" "my-pdf-file-compressed.pdf" ebook

Automate It with an Installer Script

You can install this as a command-line utility:

Tip

Make sure to chmod +x the script before running it.

#!/bin/bash

# Script to create a 'compresspdf' command that compresses PDF files
# Date: May 9, 2025

# Define colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Function to print messages
print_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check if ghostscript is installed
if ! command -v gs &> /dev/null; then
    print_error "Ghostscript (gs) is not installed. Please install ghostscript and try again."
    exit 1
fi

# Determine where to place the command
if [[ -d "$HOME/bin" && ":$PATH:" == *":$HOME/bin:"* ]]; then
    # ~/bin exists and is in PATH
    INSTALL_DIR="$HOME/bin"
elif [[ -d "$HOME/.local/bin" && ":$PATH:" == *":$HOME/.local/bin:"* ]]; then
    # ~/.local/bin exists and is in PATH
    INSTALL_DIR="$HOME/.local/bin"
else
    # Create ~/bin if it doesn't exist
    INSTALL_DIR="$HOME/bin"
    mkdir -p "$INSTALL_DIR"

    # Check if we need to update PATH
    if [[ ":$PATH:" != *":$HOME/bin:"* ]]; then
        print_step "Adding $INSTALL_DIR to your PATH..."

        # Determine which shell config file to use
        if [[ -f "$HOME/.bashrc" ]]; then
            SHELL_CONFIG="$HOME/.bashrc"
        elif [[ -f "$HOME/.bash_profile" ]]; then
            SHELL_CONFIG="$HOME/.bash_profile"
        elif [[ -f "$HOME/.zshrc" ]]; then
            SHELL_CONFIG="$HOME/.zshrc"
        else
            print_error "Could not find a shell configuration file (.bashrc, .bash_profile, or .zshrc)."
            print_error "Please manually add $INSTALL_DIR to your PATH."
            exit 1
        fi

        # Add to PATH in shell config
        echo -e "\n# Added by compresspdf command installer" >> "$SHELL_CONFIG"
        echo "export PATH=\"\$HOME/bin:\$PATH\"" >> "$SHELL_CONFIG"

        print_success "Added $INSTALL_DIR to PATH in $SHELL_CONFIG"
        print_step "Please run 'source $SHELL_CONFIG' or restart your terminal for changes to take effect."
    fi
fi

# Create the compresspdf script
COMPRESSPDF_SCRIPT="$INSTALL_DIR/compresspdf"

print_step "Creating compresspdf command at $COMPRESSPDF_SCRIPT..."

cat > "$COMPRESSPDF_SCRIPT" << 'EOF'
#!/bin/bash
# compresspdf - Compress PDF files with different quality settings
# Usage: compresspdf [input file] [output file] [screen|ebook|printer|prepress]

if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage: compresspdf [input file] [output file] [screen|ebook|printer|prepress]"
    echo "       screen   - lowest quality, smallest size (default)"
    echo "       ebook    - medium quality, good size"
    echo "       printer  - high quality, larger size"
    echo "       prepress - highest quality, largest size"
    exit 1
fi

# Check if input file exists
if [ ! -f "$1" ]; then
    echo "Error: Input file '$1' does not exist."
    exit 1
fi

# Check if input file is a PDF
if [[ ! "$1" =~ \.pdf$ ]]; then
    echo "Warning: Input file '$1' doesn't have a .pdf extension. Proceeding anyway..."
fi

# Set quality setting
QUALITY=${3:-"screen"}
case "$QUALITY" in
    screen|ebook|printer|prepress)
        ;;
    *)
        echo "Error: Invalid quality setting '$QUALITY'. Choose from: screen, ebook, printer, prepress"
        exit 1
        ;;
esac

echo "Compressing '$1' to '$2' with quality setting: $QUALITY"
gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${QUALITY} -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"

if [ $? -eq 0 ]; then
    echo "Compression successful!"

    # Calculate file sizes and compression ratio
    ORIGINAL_SIZE=$(du -h "$1" | cut -f1)
    NEW_SIZE=$(du -h "$2" | cut -f1)

    echo "Original size: $ORIGINAL_SIZE"
    echo "New size:      $NEW_SIZE"
else
    echo "Compression failed."
fi
EOF

# Make it executable
chmod +x "$COMPRESSPDF_SCRIPT"

print_success "Created compresspdf command successfully!"
print_step "You can now use the command by typing: compresspdf input.pdf output.pdf [quality]"
print_step "Quality options: screen (default), ebook, printer, prepress"

# Check if we need to remind about PATH
if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    print_step "Remember to run 'source $SHELL_CONFIG' or restart your terminal to update your PATH."
fi

# Print usage example
print_step "Example usage:"
echo "  compresspdf large-document.pdf compressed-document.pdf ebook"

print_success "Installation complete!"

[Top]

Share:
Back to Blog