压缩目录中所有pdf文件的脚本 [英] Script to compress all pdf files in a directory

查看:118
本文介绍了压缩目录中所有pdf文件的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用ghostscript将目录中的所有pdf文件压缩. 我想到了使用python读取文件 压缩pdf的gs命令是

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

这会在"/screen"处显示语法错误, 对于下面的单个文件,命令可以正常工作

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?

推荐答案

感谢您的建议tdelaney我尝试了subprocess.call,它有所帮助.下面是解决问题的代码.

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())

也可以找到... -exec是shell脚本的不错选择.

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

这篇关于压缩目录中所有pdf文件的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆