Python - PDF 转 png

网上搜了下很多方法都是过期的,这里贴下我的方法

根据 pymupdf -- Pixmap.tobytes
https://pymupdf.readthedocs.io/en/latest/pixmap.html#Pixmap.tobytes


核心方法

python 复制代码
def pdf2png(pdfPath, img_dir, zoom_x=1,zoom_y=1,rotation_angle=0):
    # 打开PDF文件
    pdf = fitz.open(pdfPath)


    # 逐页读取PDF
    for idx in range(0, pdf.page_count):
        idx += 1
        page = pdf[idx] 
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle) 
        pm = page.get_pixmap(matrix=trans, alpha=False, dpi=200)
        

        bt = pm.tobytes()
 
        img_path = os.path.join(img_dir, f'{idx}.png')
        with open(img_path, 'wb') as f:f.write(bt)
        
    pdf.close()

整个处理文件

python 复制代码
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   pdf2img.py
@Time    :   2024-09-28 11:10:57
@Author  :   shushu
@Version :   1.0
@Desc    :   
''' 

import os
import sys  
import os  
import fitz

def pdf2png(pdfPath, img_dir, zoom_x=1,zoom_y=1,rotation_angle=0):
    # 打开PDF文件
    pdf = fitz.open(pdfPath)


    # 逐页读取PDF
    for idx in range(0, pdf.page_count):
        idx += 1
        page = pdf[idx] 
        trans = fitz.Matrix(zoom_x, zoom_y).preRotate(rotation_angle) 
        pm = page.get_pixmap(matrix=trans, alpha=False)
        

        bt = pm.tobytes()
 
        img_path = os.path.join(img_dir, f'{idx}.png')
        with open(img_path, 'wb') as f:f.write(bt)
        
    pdf.close()

def test():
    pdfPath = '/Users/xxx表格_图片_page_2.pdf' 
    img_dir = '/Users/xxx/04'
    pdf2png(pdfPath, img_dir)


def prcs(file_path):
    print('-- ', file_path) 
    img_dir = file_path.replace('.pdf', '')
    if not os.path.isdir(img_dir):os.makedirs(img_dir)  
    pdf2png(file_path, img_dir)  
    
if __name__ == '__main__':
    
    paths = sys.argv[1:]
    print('-- ', paths) 
    prcs(paths) 
    
    

伊织 2024-09-28(六)

相关推荐
IOT-Power5 分钟前
QT 对话框(QDialog)中 accept、reject、exec、open的使用
开发语言·qt
froginwe117 分钟前
ASP Session
开发语言
lbb 小魔仙15 分钟前
【Python】零基础学 Python 爬虫:从原理到反爬,构建企业级爬虫系统
开发语言·爬虫·python
Swift社区16 分钟前
ArkTS Web 组件里,如何通过 javaScriptProxy 让 JS 同步调用原生方法
开发语言·前端·javascript
Q741_14717 分钟前
海致星图招聘 数据库内核研发实习生 一轮笔试 总结复盘(1) 作答语言:C/C++ 链表 二叉树
开发语言·c++·经验分享·面试·笔试
黄河里的小鲤鱼19 分钟前
拯救草台班子-战略
人工智能·python·信息可视化
秃了也弱了。21 分钟前
FASTJSON库:阿里出品java界json解析库,使用与踩坑记录
java·开发语言·json
_OP_CHEN21 分钟前
【从零开始的Qt开发指南】(十九)Qt 文件操作:从 I/O 设备到文件信息,一站式掌握跨平台文件处理
开发语言·c++·qt·前端开发·文件操作·gui开发·qt文件
Dr.Alex Wang23 分钟前
Google Firebase 实战教学 - Streamlit、Bucket、Firebase
数据库·python·安全·googlecloud
小二·24 分钟前
Python Web 全栈开发实战教程:基于 Flask 与 Layui 的待办事项系统
前端·python·flask