简介
最近要把PDF转换为png图片,用到了Python的pdf2image模块。
pdf2image是对pdftoppm和pdftocairo的封装,可以转换PDF到PIL图片对象。
安装
pip install pdf2image
windows下还需要下载poppler,并且把bin/
目录加到PATH
里。
Mac下需要安装Mac版poppler.
Linux下需要安装conda-forge
和poppler
。
conda install -c conda-forge poppler
用法
from pdf2image import convert_from_path, convert_from_bytes
from pdf2image.exceptions import (
PDFInfoNotInstalledError,
PDFPageCountError,
PDFSyntaxError
)
# 直接从文件目录读取
images = convert_from_path('/home/belval/example.pdf')
# bytes方式
images = convert_from_bytes(open('/home/belval/example.pdf', 'rb').read())
### 更好的方式
import tempfile
with tempfile.TemporaryDirectory() as path:
images_from_path = convert_from_path('/home/belval/example.pdf', output_folder=path)
# Do something here
参考
https://github.com/Belval/pdf2image