【发布时间】:2017-11-10 22:13:43
【问题描述】:
我正在尝试将包含一页或多页的 PDF 文件转换为每页的图像。这很像the question found here。事实上,我正在尝试使用该帖子中来自@Idan Yacobi 的代码来完成此操作。他的代码如下所示:
import ghostscript
def pdf2jpeg(pdf_input_path, jpeg_output_path):
args = ["pdf2jpeg", # actual value doesn't matter
"-dNOPAUSE",
"-sDEVICE=jpeg",
"-r144",
"-sOutputFile=" + jpeg_output_path,
pdf_input_path]
ghostscript.Ghostscript(*args)
当我运行代码时,我从 python 得到以下输出:
##### 238647312 c_void_p(238647312L)
当我查看应该在其中创建新 .jpg 图像的文件夹时,那里有一个具有新名称的文件。但是,当我尝试打开文件时,图像预览显示“Windows 照片查看器无法打开此图片,因为该图片正在另一个程序中编辑。”
似乎由于某种原因,Ghostscript 打开了文件并对其进行了写入,但完成后并没有关闭它。有什么办法可以强迫这种情况发生吗?或者,我是否错过了其他东西?
我已经尝试将上面的最后一行更改为下面的代码,以便在完成后显式关闭 ghostscript。
GS = ghostscript.Ghostscript(*args)
GS.exit()
【问题讨论】:
-
如果
GS = ghostscript.Ghostscript(*args)抛出异常,您的代码实际上永远不会到达GS.exit()(除非您使用finally)
标签: python pdf jpeg ghostscript