logo
December 4, 2024

Compressing PDFs with a Simple CLI Command

A neat way to do it using Ghostscript, a powerful command-line tool to compress a PDF

Have you ever needed to compress a PDF but didn’t want to use bulky software or online tools? Today, I learned about a neat way to do it using Ghostscript, a powerful command-line tool.

Why Use This?

  • No online tools needed: Perfect for privacy-conscious users.
  • Customizable: You can choose the compression level based on your needs.
  • Lightweight and fast: Ghostscript is highly efficient.
  • Main command

    Here’s the command in action:

    bash
    compresspdf() {
    gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"screen"} -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"
    }

    This little shell function, named compresspdf, takes three arguments:

  • Input file: The PDF you want to compress.
  • Output file: The compressed version of the PDF.
  • Compression level: An optional setting to control the quality of the output.
  • How It Works

    The function uses Ghostscript (gs), a versatile tool for processing PDFs and PostScript files, with the following options:

  • -sDEVICE=pdfwrite: Specifies the output as a PDF.
  • -dPDFSETTINGS: Determines the compression level. Options include:
  • -dCompatibilityLevel=1.4: Ensures the PDF is compatible with older readers.
  • -sOutputFile: Specifies the output file.
  • Bash script

    Create a bash script file compresspdf.sh with bellow content

    bash
    #!/bin/bash
    # Usage: compresspdf [input file] [output file] [screen*|ebook|printer|prepress]
    # Check that the required arguments are provided
    if [ $# -lt 2 ]; then
    echo "Usage: compresspdf [input file] [output file] [screen*|ebook|printer|prepress]"
    exit 1
    fi
    compresspdf() {
    gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"ebook"} -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"
    }
    compresspdf "$1" "$2" "$3"

    Make it executable

    bash
    chmod +x ./compresspdf.sh

    Usage

    Here’s how to use the function:

    Run it with the required arguments:

    bash
    ./compresspdf.sh input.pdf output.pdf [compression_level]

    For example:

    bash
    ./compresspdf.sh ./input.pdf ./output.pdf ebook

    If you don’t specify a compression level, it defaults to screen, which is optimized for smaller file sizes.

    Takeaway

    This function is a handy addition to any developer’s toolkit, saving time and effort while maintaining full control over PDF compression.

    Do you use a similar tool or script for handling PDFs? Let me know in the comments!