[Python] pdf to png (implemented by 13 lines of code)

Dependent modules

pip install pymupdf==1.18.9

Conversion code

import fitz


def pdf2img(pdf_path, zoom_x, zoom_y):
    doc = fitz.open(pdf_path)  # 打开文档
    for page in doc:  # 遍历页面
        pix = page.get_pixmap(matrix=fitz.Matrix(zoom_x, zoom_y))  # 将页面渲染为图片
        pix.writePNG(f'page-{page.number+1}.png')  # 将图像存储为PNG格式
    doc.close()  # 关闭文档


if __name__ == "__main__":
    pdf2img("xxx.pdf", zoom_x=3, zoom_y=3)

Parameter Description

  • pdf_path: pdfThe path of the document to be converted
  • zoom_x: xThe scaling factor of the matrix in the direction
  • zoom_y: yThe scaling factor of the matrix in the direction

NOTE: zoom_xand zoom_ygenerally take the same value, the larger the value, the higher the image resolution. (For a more detailed introduction to the matrix parameters, please see here )

Citation reference

https://pymupdf.readthedocs.io/en/latest/faq.html#how-to-make-images-from-document-pages

Guess you like

Origin blog.csdn.net/qq_42951560/article/details/114847601