如何在子进程python中传递pdf对象作为参数?

时间:2017-05-23 09:56:56

标签: python subprocess

我想将pdf文件的第一页转换为图像对象。所以想到使用子进程。子流程仅将字符串作为参数。有没有办法可以传递pdf页面对象并将图像作为输出。

示例:

而不是

import subprocess
params = ['convert','in.pdf','thumb.jpg']
subprocess.check_call(params)

我想要这样的东西

import subprocess
from PyPDF2 import PdfFileWriter, PdfFileReader

q = PdfFileReader(open("in.pdf","rb"),strict=False)
page = q.getPage(0)
params = ['convert',page,'thumb.jpg']
thumbnail = subprocess.check_call(params)

我试过但未能获得输出。有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

如果您要使用的命令不允许您通过stdin向其输入,则无法执行此操作。 (如果是这种情况,则需要将输出写入文件并将其用作输入)

另一种可能性是通过stdin传递文件,但似乎没有任何可能将PyPDF2.PageObject转换为bytes对象。如果有,请使用:

subprocess.check_call(args, stdin=to_bytes(page))

答案 1 :(得分:0)

我得到了解决方案。就像CodenameLambda说的那样将页面写入文件然后将其作为参数传递。

    import subprocess
    from PyPDF2 import PdfFileWriter, PdfFileReader

    q = PdfFileReader(open("in.pdf","rb"),strict=False)
    n = PdfFileWriter()
    n.addPage(q.getPage(0))

    with open("thumb.pdf", "wb") as outputStream:
        n.write(outputStream)

    params = ['convert','thumb.pdf','thumb.jpg']
    subprocess.check_call(params)

这将导致只有首页的缩略图。