A simple Bash script to compress PDF files on Windows.
It works by iteratively downsampling the resolution of images within the PDF to meet a desired target file size.
- Target Size Compression: Attempts to compress a PDF to a specified target size in kilobytes.
- Iterative Approach: Starts with a higher image resolution and gradually reduces it until the target file size is achieved.
- Safe: Creates a new compressed file (
<filename>_compressed.pdf) and never modifies the original. - Customizable: Easily change the target file size, and tweak resolution parameters within the script.
This script is designed to run on Windows within a Bash environment.
- Git Bash (Recommended, comes with Git for Windows).
-
Download and Install: You must have the 64-bit version of Ghostscript installed. You can download it from the official website: Ghostscript - Releases - pick the latest Win 64bit AGPL release.
-
Test the Installation: After running the
.exeinstallation file and completing the installation process, open a new Git Bash or Command Prompt window and run the following command to verify that Ghostscript is accessible:gswin64c --version
If it prints a version number, you are all set!
- Download the
compress-pdf.shscript to a folder on your computer. - Make the script executable by running the following command in your Bash terminal:
chmod +x compress-pdf.sh
For easier access from any directory, you can create an alias in your shell's configuration file (.bashrc or .bash_profile).
- Open
~/.bashrcor~/.bash_profilein a text editor. - Add the following line, replacing
~/path/to/with the actual path to the script(~ points to the folder~/Users/<UserName>):alias cp_pdf='~/path/to/compress-pdf.sh'
- The
~character is a shortcut for your user's home directory (e.g.,/c/Users/YourName). - For example, if you saved the script in
C:\Users\YourName\Scripts, the path in Git Bash would be~/Scripts/compress-pdf.sh. - If you are unsure where your
.bashrcfile is located, you can runfind ~ -maxdepth 1 -name ".bashrc"from your terminal to find it.
- The
- Save the file and restart your terminal or run
source ~/.bashrc.
Run the script from your Bash terminal, providing the name of the PDF file without the .pdf extension.
Usage: ./compress-pdf.sh [options] <filename>
| Flag | Argument | Description |
|---|---|---|
-s |
<filesize> |
Target file size in KB (default: 2000). |
-h |
Show the help message. |
Important:
- Options must come before the filename.
- The script must be run from the same directory as the PDF file.
1. Compress with default settings:
Compresses My Document.pdf to a target size of 2000 KB.
./compress-pdf.sh "My Document"2. Compress to a specific size:
Compresses Another Presentation.pdf to a target size of 800 KB.
./compress-pdf.sh -s 800 "Another Presentation"