Script to compress all pdf files in a directory

不羁的心 提交于 2019-12-06 16:13:42

问题


I wish to compress all pdf files in a directory using ghostscript. I thought of using python to read files and the gs command that compress pdf is

from __future__ import print_function
import os
for path, dirs, files in os.walk("/home/mario/books"):
    for file in files:
        if file.endswith(".pdf"):
            filename = os.path.join(root, file)
            gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=file filename

This gives syntax error at "/screen", For a single file below command works fine

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=output.pdf input.pdf

Could someone help me correcting this script or alternate solution?


回答1:


Thanks for suggestion tdelaney I tried subprocess.call which helped. Below is the code solved the problem.

from __future__ import print_function
import os
import subprocess
for root, dirs, files in os.walk("."):
for file in files:
    if file.endswith(".pdf"):
      filename = os.path.join(root, file)
      arg1= '-sOutputFile=' +"v"+ file
      p = subprocess.Popen(['/usr/bin/gs', '-sDEVICE=pdfwrite', '-dCompatibilityLevel=1.4', '-dPDFSETTINGS=/screen', '-dNOPAUSE', '-dBATCH',  '-dQUIET', str(arg1), filename], stdout=subprocess.PIPE)
      print (p.communicate())

Also find ... -exec is good option for shell script though.



来源:https://stackoverflow.com/questions/27111760/script-to-compress-all-pdf-files-in-a-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!