- Published on
Compressing PDFs with a Simple CLI Command
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?
Here’s the command in action:
bashcompresspdf() {gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"screen"} -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"}
This little shell function, named compresspdf, takes three arguments:
How It Works
The function uses Ghostscript (gs), a versatile tool for processing PDFs and PostScript files, with the following options:
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 providedif [ $# -lt 2 ]; thenecho "Usage: compresspdf [input file] [output file] [screen*|ebook|printer|prepress]"exit 1ficompresspdf() {gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${3:-"ebook"} -dCompatibilityLevel=1.4 -sOutputFile="$2" "$1"}compresspdf "$1" "$2" "$3"
Make it executable
bashchmod +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.
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!
- Published on