【问题标题】:Convert PDF file to multipage image将 PDF 文件转换为多页图像
【发布时间】:2020-08-30 20:38:18
【问题描述】:

我正在尝试使用 PyMuPDF 将多页 PDF 文件转换为图像:

pdffile = "input.pdf"
doc = fitz.open(pdffile)
page = doc.loadPage()  # number of page
pix = page.getPixmap()
output = "output.tif"
pix.writePNG(output)

但是我需要将 PDF 文件的所有页面转换为多页 tiff 中的单个图像,当我给 page 参数一个页面范围时,它只需要一页,有人知道我该怎么做吗?

【问题讨论】:

    标签: python image pdf pymupdf


    【解决方案1】:

    当您想要转换 PDF 的所有页面时,您需要一个 for 循环。此外,当您调用.getPixmap() 时,您需要像matrix = mat 这样的属性来基本上提高您的分辨率。这是代码 sn-p(不确定这是否是您想要的,但这会将所有 PDF 转换为图像):

    doc = fitz.open(pdf_file)
    zoom = 2 # to increase the resolution
    mat = fitz.Matrix(zoom, zoom)
    noOfPages = doc.pageCount
    image_folder = '/path/to/where/to/save/your/images'
    
    for pageNo in range(noOfPages):
        page = doc.loadPage(pageNo) #number of page
        pix = page.getPixmap(matrix = mat)
        
        output = image_folder + str(pageNo) + '.jpg' # you could change image format accordingly
        pix.writePNG(output)
        print('Converting PDFs to Image ... ' + output)
        # do your things afterwards
    

    对于解决方案,来自 Github 的here is a good example 演示它的含义以及它如何用于您的案例(如果需要)。

    【讨论】:

      【解决方案2】:
      import fitz
      from PIL import Image
      
      input_pdf = "input.pdf"
      output_name = "output.tif"
      compression = 'zip'  # "zip", "lzw", "group4" - need binarized image...
      
      zoom = 2 # to increase the resolution
      mat = fitz.Matrix(zoom, zoom)
      
      doc = fitz.open(input_pdf)
      image_list = []
      for page in doc:
          pix = page.getPixmap(matrix = mat)
          img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
          image_list.append(img)
          
      if image_list:
          image_list[0].save(
              output_name,
              save_all=True,
              append_images=image_list[1:],
              compression=compression,
              dpi=(300, 300),
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 2013-08-13
        • 1970-01-01
        • 2015-02-14
        • 2013-06-03
        • 1970-01-01
        相关资源
        最近更新 更多