说明
本方法提取的图片并不算完整,我测试用的是阿里2017年双十一的一份PDF,AliDouble11.pdf,提取过程中有一处报错,部分图片提取不完整
由于PyPDF2 直接提取文本内容对中文支持不友好,因此结合两个库提取
pdfplumber 可以使用 pip 安装
pip install pdfplumber
PyPDF2 需要去 GitHub 下载 https://github.com/mstamy2/PyPDF2
下载完成后解压,进入解压的目录 E:\tools\PyPDF2-master
执行 setup.py 进行安装
python setup.py install
不用pip安装的原因是 pip 下载的只更新到 1.26.0 更新日期是 2016年5月19日,只用这个版本无法提取 jpg 格式图片,会报错
Traceback (most recent call last):
File "D:/projects/util/pdf_util.py", line 106, in extract_image
data = xObject[obj].getData()
File "D:\projects\util\venv\lib\site-packages\PyPDF2\generic.py", line 844, in getData
decoded._data = filters.decodeStreamData(self)
File "D:\projects\util\venv\lib\site-packages\PyPDF2\filters.py", line 361, in decodeStreamData
raise NotImplementedError("unsupported filter %s" % filterType)
NotImplementedError: unsupported filter /DCTDecode
如果已安装 pypdf 建议先卸载 然后安装,卸载的时候最好检查是否卸载完全,即 PyPDF2 文件夹是否仍存在 ,否则可能会报错
ImportError: cannot import name 'paethPredictor'
示例代码在文件夹 PyPDF2-master\Scripts 下的 pdf-image-extractor.py
import time
import PyPDF2
import pdfplumber
from PIL import Image
def extract_image(page):
try:
# 提取第2页图片(从0开始计数)
page_image = pdf_image_reader.getPage(pageNumber=1)
extract_image(page_image)
if '/XObject' in page['/Resources']:
xObject = page['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
# 保存图片的文件名前缀
img_pre = str(int(time.time()*1000))
if '/Filter' in xObject[obj]:
if xObject[obj]['/Filter'] == '/FlateDecode':
img = Image.frombytes(mode, size, data)
img.save(img_pre + ".png")
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(img_pre + ".jpg", "wb")
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(img_pre + ".jp2", "wb")
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
img = open(img_pre + ".tiff", "wb")
img.write(data)
img.close()
else:
img = Image.frombytes(mode, size, data)
img.save(img_pre + ".png")
else:
print("本页无图片")
except:
print("图片提取失败")
def extract_content(pdf_path):
# 内容提取,使用 pdfplumber 打开 PDF,用于提取文本
with pdfplumber.open(pdf_path) as pdf_file:
# 使用 PyPDF2 打开 PDF 用于提取图片
pdf_image_reader = PyPDF2.PdfFileReader(open(pdf_path, "rb"))
print(pdf_image_reader.getNumPages())
content = ''
# len(pdf.pages)为PDF文档页数,一页页解析
for i in range(len(pdf_file.pages)):
print("当前第 %s 页" % i)
# pdf.pages[i] 是读取PDF文档第i+1页
page_text = pdf_file.pages[i]
# page.extract_text()函数即读取文本内容
page_content = page_text.extract_text()
if page_content:
content = content + page_content + "\n"
print(page_content)
import time
import PyPDF2
import pdfplumber
from PIL import Image
def extract_image(page):
try:
if '/XObject' in page['/Resources']:
xObject = page['/Resources']['/XObject'].getObject()
for obj in xObject:
if xObject[obj]['/Subtype'] == '/Image':
size = (xObject[obj]['/Width'], xObject[obj]['/Height'])
data = xObject[obj].getData()
if xObject[obj]['/ColorSpace'] == '/DeviceRGB':
mode = "RGB"
else:
mode = "P"
# 保存图片的文件名前缀
img_pre = str(int(time.time()*1000))
if '/Filter' in xObject[obj]:
if xObject[obj]['/Filter'] == '/FlateDecode':
img = Image.frombytes(mode, size, data)
img.save(img_pre + ".png")
elif xObject[obj]['/Filter'] == '/DCTDecode':
img = open(img_pre + ".jpg", "wb")
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/JPXDecode':
img = open(img_pre + ".jp2", "wb")
img.write(data)
img.close()
elif xObject[obj]['/Filter'] == '/CCITTFaxDecode':
img = open(img_pre + ".tiff", "wb")
img.write(data)
img.close()
else:
img = Image.frombytes(mode, size, data)
img.save(img_pre + ".png")
else:
print("本页无图片")
except:
print("图片提取失败")
def extract_content(pdf_path):
# 内容提取,使用 pdfplumber 打开 PDF,用于提取文本
with pdfplumber.open(pdf_path) as pdf_file:
# 使用 PyPDF2 打开 PDF 用于提取图片
pdf_image_reader = PyPDF2.PdfFileReader(open(pdf_path, "rb"))
print(pdf_image_reader.getNumPages())
content = ''
# len(pdf.pages)为PDF文档页数,一页页解析
for i in range(len(pdf_file.pages)):
print("当前第 %s 页" % i)
# pdf.pages[i] 是读取PDF文档第i+1页
page_text = pdf_file.pages[i]
# page.extract_text()函数即读取文本内容
page_content = page_text.extract_text()
if page_content:
content = content + page_content + "\n"
print(page_content)
# 提取图片
page_image = pdf_image_reader.getPage(pageNumber=i)
extract_image(page_image)
if __name__ == '__main__':
pdf_file = "../media/AliDouble11.pdf"
extract_content(pdf_file)