使用pdfplumber库处理pdf文件获取文本图片作者等信息

复制代码
   To use the `pdfplumber` library to extract content from PDF files in Python, follow these steps with example code:

1. Install pdfplumber 库安装

First, install the library using pip:

bash 复制代码
pip install pdfplumber

2. Basic Text Extraction获取文本

Extract all text from a PDF file:

python 复制代码
import pdfplumber

# Replace with your PDF file path (use raw string or double backslashes on Windows)
pdf_path = r'c:\Users\czliu\Documents\python\example.pdf'

# Extract all text from PDF
with pdfplumber.open(pdf_path) as pdf:
    all_text = ''
    for page in pdf.pages:
        all_text += page.extract_text() + '\n'

print("Extracted Text:")
print(all_text)

3. Extract Text from Specific Pages获取指定的页内容

Extract text from page 2 (0-indexed, so page 1 is index 0):

python 复制代码
import pdfplumber

pdf_path = r'c:\Users\czliu\Documents\python\example.pdf'

with pdfplumber.open(pdf_path) as pdf:
    # Extract text from page 2 (index 1)
    page = pdf.pages[1]
    page_text = page.extract_text()
    
    print("Text from Page 2:")
    print(page_text)

4. Extract Tables (pdfplumber's Key Feature) 获取表格

pdfplumber excels at extracting structured tables. Example with table extraction:

python 复制代码
import pdfplumber
import pandas as pd  # Optional, for better table handling

pdf_path = r'c:\Users\czliu\Documents\python\example.pdf'

with pdfplumber.open(pdf_path) as pdf:
    for page_num, page in enumerate(pdf.pages, 1):
        # Extract tables from current page
        tables = page.extract_tables()
        
        if tables:
            print(f"\n--- Tables from Page {page_num} ---")
            for table_idx, table in enumerate(tables):
                print(f"\nTable {table_idx + 1}:")
                
                # Print raw table data
                for row in table:
                    print(row)
                
                # Optional: Convert to pandas DataFrame for better manipulation
                df = pd.DataFrame(table[1:], columns=table[0])  # Assume first row is header
                print(f"\nDataFrame for Table {table_idx + 1}:")
                print(df)

5. Extract PDF Metadata 获取作者、创建时间等信息

Get document information like author, title, creation date:

python 复制代码
import pdfplumber

pdf_path = r'c:\Users\czliu\Documents\python\example.pdf'

with pdfplumber.open(pdf_path) as pdf:
    metadata = pdf.metadata
    print("PDF Metadata:")
    for key, value in metadata.items():
        print(f"{key}: {value}")

6. Extract Images (Advanced)获取图片内容并存盘

Extract images embedded in the PDF:

python 复制代码
import pdfplumber
import pillow as pw  # Optional, for image saving
pdf_path = r'c:\Users\czliu\Documents\python\example.pdf'

with pdfplumber.open(pdf_path) as pdf:
    for page_num, page in enumerate(pdf.pages, 1):
        images = page.images
        if images:
            print(f"\n--- Images from Page {page_num} ---")
            for img_idx, img in enumerate(images):
             	  pw.Image.save(img, f"page{page_num}_img{img_idx + 1}.png")   # Save image
                print(f"Image {img_idx + 1}:")
                print(f"  Coordinates: {img['bbox']}")
                print(f"  Width: {img['width']}, Height: {img['height']}")
                # Note: To save images, you'll need additional libraries like PIL

Notes:

  • On Windows, use raw strings (r'path') or double backslashes ('c:\\Users\\...') for file paths.
  • pdfplumber's table extraction uses camelot's algorithm under the hood and can be customized with table_settings (e.g., table_settings={"vertical_strategy": "lines", "horizontal_strategy": "lines"}).
  • For scanned PDFs, you'll need OCR tools like Tesseract (pdfplumber alone won't work for scanned text).
相关推荐
AOwhisky15 小时前
Python 学习笔记(第十四期)——运维自动化(下·中篇):远程文件传输——paramiko进阶篇
运维·python·学习·云原生·自动化·文件传输·paramiko
其实防守也摸鱼15 小时前
补天SRC新手入门指南:从0到1的漏洞挖掘之路
网络·python·学习·安全·web安全·数据挖掘·挖洞
lupai15 小时前
手机在网状态查询 API 新手实战指南
大数据·python·智能手机
其美杰布-富贵-李16 小时前
Spring Boot 依赖注入说明文档
java·spring boot·python
梦想的初衷~16 小时前
植被遥感反演与数据同化算法体系教程:从PROSAIL前向模拟到作物估产
人工智能·python·机器学习·作物模型·遥感数据同化·prosail·植被参数反演
LadenKiller17 小时前
近期AI协作写量化规则,要按阶段安排任务
人工智能·python
天天进步201517 小时前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
ellenwan202617 小时前
近期AI协作量化实现,先补规则清晰度和流程完整性
人工智能·python
卷无止境17 小时前
Python 类型注解与运行时反射:从原理到工程实践
后端·python
酷可达拉斯17 小时前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算