Python——批量将PDF文件转为图片

2024-08-15 13:26:31 浏览数 (1)

前言

这里是只将pdf文件的前两页进行了转换;

内容

代码语言:javascript复制
import fitz  # pip install pymupdf
import os


def pdf2img(pdf_path, zoom_x, zoom_y):
    doc = fitz.open(pdf_path) 
    for page in doc: 
        print(page.number)
        pic = page.get_pixmap(matrix=fitz.Matrix(zoom_x, zoom_y)) 
        dir_save = os.path.dirname(pdf_path) 
        pdf_name = os.path.basename(pdf_path).split('.pdf')[0]
        pic.save(f'{dir_save}/{pdf_name}-page-{page.number   1}.png') 
        if page.number == 1: 
            break
    doc.close()


for root, dirs, files in os.walk(r"C:UsersWangYangDesktop资料"):
    for file in files:
        if os.path.splitext(file)[1] == '.pdf':
            # print(file)
            pdf2img(
                os.path.join(root, file),
                zoom_x=3,
                zoom_y=3
            )

0 人点赞