python pdf转图片
2022/1/31 20:12:52
本文主要是介绍python pdf转图片,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
需求
将pdf的第一页即为封面转为图片。
所有pdf在同一个目录下,
生成的图片在同目录下的img文件夹内。
图片命名即为pdf的名字。
使用
pip install PyPDF2
pip install pdf2image
同时下载poppler,下载地址是:
https://blog.alivate.com.au/wp-content/uploads/2018/08/poppler-0.67.0_x86.7z
解压压缩包,将poppler/bin/ 目录添加至电脑的path的环境变量里。
注意一定要重启!否则没有生效
代码
from PyPDF2 import PdfFileReader, PdfFileWriter import glob import os from pdf2image import convert_from_path import shutil def pdf2image2(pdfPath, imagePath): images = convert_from_path(pdfPath, dpi=96) for image in images: if not os.path.exists(imagePath): os.makedirs(imagePath) pngname=pdfPath[6:-4] image.save(imagePath+'/'+pngname+'.png', 'PNG') def process_bar(no, total_length): bar = '\r' + str(no) + '|' + str(total_length) print(bar, end='', flush=True) def split_combine(path, pdf_writer): pdf = PdfFileReader(path, strict=False) # lastest page page = pdf.getPage(0) pdf_writer.addPage(page) if __name__ == '__main__': # get curren dir pdf files pdf_list = glob.glob('*.pdf') pdf_writer = PdfFileWriter() imgpath="./img/" tmppath="./tmp/" if not os.path.exists(imgpath): os.makedirs(imgpath) if not os.path.exists(tmppath): os.makedirs(tmppath) for i, pdf_file in enumerate(pdf_list): process_bar(i + 1, len(pdf_list)) split_combine(pdf_file, pdf_writer) with open(tmppath+pdf_file, 'wb') as output_pdf: pdf_writer.write(output_pdf) pdf2image2(tmppath+pdf_file, imgpath) shutil.rmtree(tmppath)
这篇关于python pdf转图片的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python