多线程运行将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)