Welcome folks today in this blog post we will be writing a simple shell bat
script to compress multiple large size pdf documents in command line. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the ghostscript
pdf compression library in windows 10 or 11 as shown below in the blog post. You need to read this blog post as shown below
How to Install GhostScript PDF Compression Library on Command Line in Windows 11 & 10
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
from __future__ import print_function import os import subprocess root = "." try: os.mkdir('compressed') except FileExistsError: pass for file in os.listdir(root): if file.endswith(".pdf"): filename = os.path.join(root, file) arg1= '-sOutputFile=' + './compressed/' + file print ("compressing:", file ) p = subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4', '-dPDFSETTINGS=/screen', '-dNOPAUSE', '-dBATCH', '-dQUIET', str(arg1), filename], stdout=subprocess.PIPE).wait() |
If you execute the above python
script then the compressed
folder will be created as shown above.
Now you need to create the compress.bat
file and copy paste the following code
compress.bat
1 2 3 4 5 |
@echo off setlocal set GS_OUTPUT_DIR=compressed_files mkdir %GS_OUTPUT_DIR% for %%i in (*.pdf) do ps2pdf -dPDFSETTINGS#/screen "%%i" "%GS_OUTPUT_DIR%\%%i" |