将 pdf 文件页面转换为图像 - Wand

convert pdf file pages to images - Wand

初学者:

我的代码 运行 当我只将它用于一个 pdf 时没问题,但是一旦我添加了一个 for 循环,代码仍然 运行s 但它只是转换了第一页pdf 多页 pdf 而不是全部。

例如,如果我的 pdf 是 xyz.pdf,有 2 页,它会将两页都转换为 jpg 并单独输出。但是一旦我 运行 我的 pdf xyz 和 abc 代码,它只会转换两个 pdf 的第一页。

我在这里错过了什么?

from wand.image import Image as wi

for pdf_file in os.listdir(pdf_dir):                               
  if pdf_file.endswith(".pdf"):
   pdf = wi(filename= os.path.join(pdf_dir, pdf_file), resolution=300)
   pdfimage = pdf.convert("jpeg")
   i=1
   for img in pdfimage.sequence:
     page = wi(image=img)
     page.save(filename=os.path.join(pdf_dir, str(pdf_file[:-4] +".jpg")))
     i +=1

适用于我:

def convert_pdf(filename, output_path, resolution=150):
    all_pages = wi(filename=filename, resolution=resolution)
    for i, page in enumerate(all_pages.sequence):
        with wi(page) as img:
            image_filename = os.path.splitext(os.path.basename(filename))[0]
            image_filename = '{}-{}.jpg'.format(image_filename, i)
            image_filename = os.path.join(output_path, image_filename)

            img.save(filename=image_filename)


for pdf_file in os.listdir(pdf_dir):
    if pdf_file.endswith(".pdf"):
        convert_pdf(os.path.join(pdf_dir, pdf_file), pdf_dir)