- Published on
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:
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:
- screen (default): Low resolution for online viewing.
- ebook: Medium resolution for eBooks.
- printer: High resolution for printing.
- prepress: Maximum quality for professional printing.
- -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
#!/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
chmod +x ./compresspdf.sh
Usage
Here’s how to use the function:
Run it with the required arguments:
./compresspdf.sh input.pdf output.pdf [compression_level]
For example:
./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!