当前位置: 首页 > news >正文

Python使用PDF相关组件案例详解

主要对pdfminer.sixpdfplumberPyMuPDFPyPDF2PyPDF4pdf2imagecamelot-py七个PDF相关组件分别详解,具体使用案例演示

1. pdfminer.six
pdfminer.six 是一个专门用来从 PDF 中提取文本的库,能够处理复杂的文本布局,适合用于文本解析,尤其是需要了解 PDF 页面的结构时。

安装:

pip install pdfminer.six

使用案例:

from pdfminer.high_level import extract_text
try:# 提取 PDF 文件的文本text = extract_text('example.pdf')print(text)
except Exception as e:print(f"Error extracting text: {e}")

注意事项:

•	适合于文本内容的提取,特别是有复杂布局的文档。
•	对于表格或图像提取的支持较弱。
•	文本提取时可能会丢失一些排版信息。

异常处理案例:

from pdfminer.high_level import extract_textdef extract_pdf_text(file_path):try:text = extract_text(file_path)return textexcept FileNotFoundError:print("The specified file does not exist.")except Exception as e:print(f"Error: {e}")# 测试
file_path = 'non_existing_file.pdf'
text = extract_pdf_text(file_path)

2. pdfplumber

pdfplumber 是一个基于 pdfminer.six 的工具,专门用于提取 PDF 中的表格、文本、图像等结构化内容。

安装:

pip install pdfplumber

使用案例:

import pdfplumbertry:# 打开 PDF 文件with pdfplumber.open("example.pdf") as pdf:first_page = pdf.pages[0]# 提取文本text = first_page.extract_text()print(text)# 提取表格table = first_page.extract_table()for row in table:print(row)
except Exception as e:print(f"Error processing PDF: {e}")

注意事项:

•	对于 PDF 中的表格提取有较好的支持。
•	解析结构复杂的表格时可能需要进一步的调整和处理。
•	不适用于处理扫描版 PDF。

异常处理案例:

import pdfplumberdef extract_table_from_pdf(file_path):try:with pdfplumber.open(file_path) as pdf:first_page = pdf.pages[0]table = first_page.extract_table()return tableexcept pdfplumber.utils.PDFPlumberException as e:print(f"Error in pdfplumber: {e}")except Exception as e:print(f"Error: {e}")# 测试
table = extract_table_from_pdf('non_existing_file.pdf')

3. PyMuPDF (fitz)

PyMuPDF 是一个强大的 PDF、XPS、EPUB 等格式的文档处理库,支持提取文本、图像和页面渲染等多种功能。

安装:

pip install PyMuPDF

使用案例:

import fitz  # PyMuPDF 的别名try:# 打开 PDF 文件doc = fitz.open("example.pdf")# 提取文本for page in doc:text = page.get_text()print(text)# 提取图像for page in doc:images = page.get_images(full=True)for img in images:print(img)
except Exception as e:print(f"Error processing PDF: {e}")

注意事项:

•	可以提取文本、图像、并进行页面渲染。
•	对于扫描版 PDF,可以通过 OCR 结合其他工具进行文本提取。
•	需要安装 pillow 来处理图像。

异常处理案例:

import fitzdef extract_text_from_pdf(file_path):try:doc = fitz.open(file_path)text = ""for page in doc:text += page.get_text()return textexcept Exception as e:print(f"Error: {e}")return None# 测试
text = extract_text_from_pdf('non_existing_file.pdf')

4. PyPDF2

PyPDF2 是一个用于 PDF 文档操作的库,支持 PDF 文件的合并、拆分、旋转、裁剪等。

安装:

pip install PyPDF2

使用案例:

from PyPDF2 import PdfReader, PdfWritertry:# 读取 PDF 文件reader = PdfReader('example.pdf')writer = PdfWriter()# 提取第一页的文本page = reader.pages[0]print(page.extract_text())# 合并 PDF 文件writer.add_page(reader.pages[0])with open('output.pdf', 'wb') as output_pdf:writer.write(output_pdf)
except Exception as e:print(f"Error processing PDF: {e}")

注意事项:

•	适合于 PDF 的合并、拆分、旋转、裁剪等操作。
•	不支持图像或表格提取。
•	对于扫描版 PDF,提取文本效果不佳。

异常处理案例:

from PyPDF2 import PdfReaderdef merge_pdfs(input_files, output_file):try:writer = PdfWriter()for file in input_files:reader = PdfReader(file)for page in reader.pages:writer.add_page(page)with open(output_file, 'wb') as output:writer.write(output)except FileNotFoundError as e:print(f"Error: {e}")except Exception as e:print(f"Error: {e}")# 测试
merge_pdfs(['non_existing_file.pdf'], 'merged.pdf')

5. PyPDF4

PyPDF4 是 PyPDF2 的分支,提供了更好的功能,特别是对于处理加密的 PDF 文件。

安装:

pip install PyPDF4

使用案例:

import PyPDF4try:# 读取 PDF 文件with open('example.pdf', 'rb') as f:reader = PyPDF4.PdfReader(f)writer = PyPDF4.PdfWriter()# 提取第一页的文本page = reader.pages[0]print(page.extract_text())# 合并多个文件writer.add_page(reader.pages[0])with open('output.pdf', 'wb') as output_f:writer.write(output_f)
except Exception as e:print(f"Error processing PDF: {e}")

注意事项:

•	功能与 PyPDF2 类似,改进了处理加密文件的能力。
•	不支持表格或图像提取。

异常处理案例:

import PyPDF4def split_pdf(input_pdf, output_pdf):try:with open(input_pdf, 'rb') as in_file:reader = PyPDF4.PdfReader(in_file)writer = PyPDF4.PdfWriter()writer.add_page(reader.pages[0])  # 只提取第一页with open(output_pdf, 'wb') as out_file:writer.write(out_file)except Exception as e:print(f"Error: {e}")# 测试
split_pdf('non_existing_file.pdf', 'output.pdf')

6. pdf2image

pdf2image 可以将 PDF 页面转换为图像,适用于需要将 PDF 页面呈现为图像的情况。

安装:

pip install pdf2image

使用案例:

from pdf2image import convert_from_pathtry:# 将 PDF 页面转换为图像images = convert_from_path('example.pdf')# 保存为图像文件for i, image in enumerate(images):image.save(f'page_{i+1}.png', 'PNG')
except Exception as e:print(f"Error converting PDF to image: {e}")

注意事项:

•	适合将 PDF 页面转换为图像文件(如 PNG、JPEG)。
•	需要额外安装 poppler-utils。
•	高质量转换可能会导致内存占用较大。

异常处理案例:

from pdf2image import convert_from_pathdef convert_pdf_to_images(file_path):try:images = convert_from_path(file_path)return imagesexcept Exception as e:print(f"Error: {e}")return []# 测试
images = convert_pdf_to_images('non_existing_file.pdf')

7. camelot-py

camelot-py 是一个专门用来提取 PDF 中表格数据的库,能够很好地处理带有表格的 PDF 文件。

安装:

pip install camelot-py[cv]

使用案例:

import camelottry:# 提取 PDF 文件中的表格tables = camelot.read_pdf('example.pdf', pages='1')# 显示第一张表格print(tables[0].df)
except Exception as e:print(f"Error extracting table: {e}")

注意事项:

•	适合用于表格提取,尤其是结构清晰的表格。
•	对于复杂或不规则的表格,需要调整模式(lattice 或 stream)。

异常处理案例:

import camelotdef extract_table_from_pdf(file_path):try:tables = camelot.read_pdf(file_path, pages='1')return tables[0].dfexcept camelot.utils.PDFPageCountError as e:print(f"Page count error: {e}")except Exception as e:print(f"Error: {e}")return None# 测试
table = extract_table_from_pdf('non_existing_file.pdf')

总结

•	文本提取: 使用 pdfminer.six 或 PyMuPDF。
•	表格提取: pdfplumber 和 camelot-py 适合表格提取。
•	PDF 操作: PyPDF2 和 PyPDF4 适用于合并、拆分、裁剪等。
•	图像转换: 使用 pdf2image 来将 PDF 转为图像。

对于每个组件库,异常处理能够帮助应对文件不存在、格式错误等常见问题。

http://www.lryc.cn/news/478802.html

相关文章:

  • day53 图论章节刷题Part05(并查集理论基础、寻找存在的路径)
  • 鸿蒙next选择 Flutter 开发跨平台应用的原因
  • shodan6-7---清风
  • FTP、ISCSI、CHRONY、DNS、NFS、DOCKER、MARIADB、NGINX、PHP、CA各服务开启方法
  • 抢先体验AI领域的新宠儿:Llama3.1,部署实战探索!
  • HarmonyOS基础:鸿蒙系统组件导航Navigation
  • 【K8S问题系列】Kubernetes 中 Pod 无法通过 Service 名称访问服务的 DNS 解析失败【已解决】
  • 【下载工具】Internet Download Manager下载器介绍
  • 如何打开/关闭 GitLab 的版本检查功能?
  • java-web-day13-事务管理+spring aop
  • MySQL详细安装教程
  • 文件系统和日志管理
  • 【LeetCode】【算法】208. 实现 Trie (前缀树)
  • libaom 源码分析:帧间运动矢量预测
  • Android TextView自动换行文本显示不全解决
  • 【LeetCode】【算法】394. 字符串解码
  • 最新整理:Selenium自动化测试面试题
  • 外包干了2年,快要废了。。。
  • 乐尚代驾十订单支付seata、rabbitmq异步消息、redisson延迟队列
  • HCIP--3实验- 链路聚合,VLAN间通讯,Super VLAN,MSTP,VRRPip配置,静态路由,环回,缺省,空接口,NAT
  • Apple提出MM1.5:多模态大型语言模型微调的方法、分析和见解_mm1.5 模型下载
  • 【毫米波雷达(三)】汽车控制器启动流程——BootLoader
  • AI 搜索来势汹汹,互联网将被颠覆还是进化?
  • 《二分查找算法:在有序数组中搜索目标值》
  • 【万字总结】数据结构常考应用大题做法画法详解_树_哈希表_图_排序大总结
  • Docker + Jenkins + gitee 实现CICD环境搭建
  • rabbitMq怎么保证消息不丢失?消费者没有接收到消息怎么处理
  • 商务数据分析在提升客户体验方面的作用体现在哪些环节
  • cooladmin使用整理
  • CentOS 7 更换软件仓库