I am using this script below, taken from here: https://github.com/theeko74/pdfc/blob/master/pdf_compressor.py
import os
import sys
import subprocess
def compress(input_file_path, output_file_path, power=0):
"""Function to compress PDF via Ghostscript command line interface"""
quality = {
0: '/default',
1: '/prepress',
2: '/printer',
3: '/ebook',
4: '/screen'
}
# Basic controls
# Check if valid path
if not os.path.isfile(input_file_path):
print("Error: invalid path for input PDF file")
sys.exit(1)
# Check if file is a PDF by extension
if input_file_path.split('.')[-1].lower() != 'pdf':
print("Error: input file is not a PDF")
sys.exit(1)
print("Compress PDF...")
initial_size = os.path.getsize(input_file_path)
subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path])
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")
I want to use it to compress a PDF, however when ever it was run the below error was produced:
Traceback (most recent call last):
File "D:/Documents/Pdf Handler/compress.py", line 39, in <module>
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")
File "D:/Documents/Pdf Handler/compress.py", line 31, in compress
input_file_path]
File "C:\Python37\lib\subprocess.py", line 323, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python37\lib\subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "C:\Python37\lib\subprocess.py", line 1178, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
After some research, i found out that i had to add shell=True in subprocess.call:
...
print("Compress PDF...")
initial_size = os.path.getsize(input_file_path)
subprocess.Popen(['gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4',
'-dPDFSETTINGS={}'.format(quality[power]),
'-dNOPAUSE', '-dQUIET', '-dBATCH',
'-sOutputFile={}'.format(output_file_path),
input_file_path])
compress("D:/Documents/Pdf Handler/test.pdf","D:/Documents/Pdf Handler/testCompress.pdf")
whilst this did fix the issue of an error being raised, the code now doesn't appear to actually do anything. It runs, however no files are added to the specified directory.
Your help would be massively appreciated, as i mentioned i did take this code from elsewhere and the documentation is very sparse.