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

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

1. pdfminer.six

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

安装:

bash 复制代码
pip install pdfminer.six

使用案例:

python 复制代码
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}")

注意事项:

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

异常处理案例:

python 复制代码
from pdfminer.high_level import extract_text

def extract_pdf_text(file_path):
    try:
        text = extract_text(file_path)
        return text
    except 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 中的表格、文本、图像等结构化内容。

安装:

bash 复制代码
pip install pdfplumber

使用案例:

python 复制代码
import pdfplumber

try:
    # 打开 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。

异常处理案例:

python 复制代码
import pdfplumber

def 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 table
    except 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 等格式的文档处理库,支持提取文本、图像和页面渲染等多种功能。

安装:

bash 复制代码
pip install PyMuPDF

使用案例:

python 复制代码
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 来处理图像。

异常处理案例:

python 复制代码
import fitz

def extract_text_from_pdf(file_path):
    try:
        doc = fitz.open(file_path)
        text = ""
        for page in doc:
            text += page.get_text()
        return text
    except Exception as e:
        print(f"Error: {e}")
        return None

# 测试
text = extract_text_from_pdf('non_existing_file.pdf')

4. PyPDF2

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

安装:

bash 复制代码
pip install PyPDF2

使用案例:

python 复制代码
from PyPDF2 import PdfReader, PdfWriter

try:
    # 读取 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,提取文本效果不佳。

异常处理案例:

python 复制代码
from PyPDF2 import PdfReader

def 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 文件。

安装:

bash 复制代码
pip install PyPDF4

使用案例:

python 复制代码
import PyPDF4

try:
    # 读取 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 类似,改进了处理加密文件的能力。
•	不支持表格或图像提取。

异常处理案例:

python 复制代码
import PyPDF4

def 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 页面呈现为图像的情况。

安装:

bash 复制代码
pip install pdf2image

使用案例:

python 复制代码
from pdf2image import convert_from_path

try:
    # 将 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。
•	高质量转换可能会导致内存占用较大。

异常处理案例:

python 复制代码
from pdf2image import convert_from_path

def convert_pdf_to_images(file_path):
    try:
        images = convert_from_path(file_path)
        return images
    except Exception as e:
        print(f"Error: {e}")
        return []

# 测试
images = convert_pdf_to_images('non_existing_file.pdf')

7. camelot-py

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

安装:

bash 复制代码
pip install camelot-py[cv]

使用案例:

python 复制代码
import camelot

try:
    # 提取 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)。

异常处理案例:

python 复制代码
import camelot

def extract_table_from_pdf(file_path):
    try:
        tables = camelot.read_pdf(file_path, pages='1')
        return tables[0].df
    except 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 转为图像。

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

相关推荐
databook4 小时前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar5 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780515 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_5 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
数据智能老司机12 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机13 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机13 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机13 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i13 小时前
drf初步梳理
python·django
每日AI新事件13 小时前
python的异步函数
python