Skip to content

Instantly share code, notes, and snippets.

@sanchit3008
Last active January 16, 2021 10:06
Show Gist options
  • Save sanchit3008/b4d6c2197885d95082d0d833f0721904 to your computer and use it in GitHub Desktop.
Save sanchit3008/b4d6c2197885d95082d0d833f0721904 to your computer and use it in GitHub Desktop.
PDF Compression in Windows using Python and Ghostscript
import os
import time
'''
1. Download https://github.com/ArtifexSoftware/ghostpdl-downloads/releases/download/gs9533/gs9533w64.exe
2. Install Ghostscript from the exe.
3. Confirm that gswin64c.exe is present in C:\\Program Files\\gs\\gs9.53.3\\bin
4. Place this python file in a folder containing all the PDFs to be compressed.
5. Run 'python compress.py' from a command prompt (don't use powershell).
6. Compressed files will be saved in 'Compressed' subfolder.
'''
startTime = time.time()
ghostscriptPath = 'C:\\PROGRA~1\\gs\\gs9.53.3\\bin\\gswin64c.exe '
ghostscriptParams = "-sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -q "
inputFiles = [x for x in os.listdir() if x.endswith(".pdf")]
fileCount = 0
if len(inputFiles) > 0 and not os.path.exists('Compressed'):
os.makedirs('Compressed')
print("Compressing " + str(len(inputFiles)) + " file(s).\n")
for inputFile in sorted(inputFiles):
fileCount += 1
outputFileParam = '-o "Compressed/' + inputFile[:-4] + '_Compressed.pdf" '
inputFile = '"' + inputFile + '"'
cmd = ghostscriptPath + ghostscriptParams + outputFileParam + inputFile
print(str(fileCount) + ". " + inputFile)
os.system(cmd)
endTime = time.time()
print("\nCompleted. Time Taken: " + str(round(endTime - startTime, 2)) + " seconds.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment