多线程将 PDF 文件转换成 Image 文件,按页升序保存

多线程运行将PDF转换成Image文件

目标

将PDF文件按页转换成图像文件格式,每页一个jpg文件,且按照页码升序排列。问文本自动识别 OCR 做准备。

采用库

采用pdf2image 软件包,主要是 convert_from_path 转换函数。

特点

采用多线程,设置 thread_count=3, 线程数不要超过4,以免死锁,dpi取默认值200 较好。

代码

import os
from sys import argv
import time
from pdf2image import convert_from_path #, convert_from_bytes
#import tempfile
from pdf2image.exceptions import (
    PDFInfoNotInstalledError,
    PDFPageCountError,
    PDFSyntaxError
)

if __name__ == "__main__":
    if len(argv) > 1:
        start = time.time()
        pdfPath = argv[1]

        if not os.path.isfile(pdfPath): 
            print("输入的文件{0}不存在!".format(pdfPath))
            exit()

        imagePath = argv[1].split(sep='.')[0] 
        #if len(imagePath) ==0: imagePath = "temp_img"
        if not os.path.exists(imagePath):
            os.makedirs(imagePath)
        
        print("处理{0}...".format(pdfPath))

        # 一条命令搞定pdf到image文件的转换
        convert_from_path(pdfPath, dpi=200, output_folder=imagePath, fmt='jpg', output_file='pix', thread_count=3)

        print("运行{0},耗时{1}秒!".format(pdfPath, time.time()-start))
    else:
        print("""
        使用说明:python pdf2img.py pdf文件名
        使用举例:python pdf2img.py test.pdf
        """)    

结果

1000页的PDF大概 70秒完成。

参数说明

convert_from_path(pdf_path, dpi=200, output_folder=None, first_page=None, last_page=None, fmt='ppm', jpegopt=None, thread_count=1, userpw=None, use_cropbox=False, strict=False, transparent=False, single_file=False, output_file=<pdf2image.generators.ThreadSafeGenerator object at 0x00000267CFF9E8E0>, poppler_path=None, grayscale=False, size=None, paths_only=False, use_pdftocairo=False, timeout=None, hide_annotations=False)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值