Я использую этот скрипт ниже, взятый отсюда: 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")
Я хочу использовать его для сжатия PDF, однако когда-либо он запускался ниже Произошла ошибка:
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
После некоторых исследований я обнаружил, что мне нужно было добавить shell = True в 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")
, хотя это действительно решило проблему ошибка возникает, код, похоже, на самом деле ничего не делает. Он запускается, однако в указанный каталог файлы не добавляются.
Ваша помощь будет чрезвычайно полезна, так как я уже говорил, что этот код брал откуда-то еще, а документация очень скудная.