用Python将 PDF 中的表格提取为 Excel/CSV
*用Python将 PDF 中的表格提取为 Excel/CSV,*支持文本型 PDF 和 扫描件/图片型 PDF(需 OCR 识别)。程序包含以下功能:
1.自动检测 PDF 类型(文本 or 扫描件)
2.提取表格数据并保存为 Excel/CSV
3.处理多页 PDF
4.命令行交互 & 图形界面(可选)
1. 安装依赖库
运行前,先安装所需库:
pip install tabula-py pandas pytesseract pdf2image opencv-python pillow
2. 完整代码
导入相关模块
import os
import pandas as pd
import tabula
from pdf2image import convert_from_path
import pytesseract
import cv2
import tempfile
import argparse
定义函数
def pdf_to_excel(pdf_path, output_path, use_ocr=False):
"""将 PDF 中的表格转换为 Excel 文件:param pdf_path: PDF 文件路径:param output_path: 输出 Excel/CSV 路径:param use_ocr: 是否强制使用 OCR(针对扫描件)"""try:# 检查输出格式file_ext = os.path.splitext(output_path)[1].lower()if file_ext not in ['.xlsx', '.csv']:raise ValueError("输出文件格式必须是 .xlsx 或 .csv")
# 尝试直接提取文本表格(非扫描件)if not use_ocr:try:print("尝试提取文本表格...")dfs = tabula.read_pdf(pdf_path, pages='all', multiple_tables=True)if not dfs:raise RuntimeError("未检测到表格,可能为扫描件图片。")# 合并所有表格页combined_df = pd.concat(dfs, ignore_index=True)if file_ext == '.xlsx':combined_df.to_excel(output_path, index=False)else:combined_df.to_csv(output_path, index=False)print(f"转换成功!结果已保存至: {output_path}")returnexcept Exception as e:print(f"文本提取失败(可能为扫描件),尝试 OCR: {e}")use_ocr = True
# OCR 处理扫描件/图片if use_ocr:print("正在使用 OCR 识别扫描件...")with tempfile.TemporaryDirectory() as temp_dir:# 将 PDF 转换为图片images = convert_from_path(pdf_path, output_folder=temp_dir)all_text = []for i, img in enumerate(images):img_path = os.path.join(temp_dir, f"page_{i+1}.jpg")img.save(img_path, 'JPEG')# 使用 OpenCV 增强图像(可选)img_cv = cv2.imread(img_path)gray = cv2.cvtColor(img_cv, cv2.COLOR_BGR2GRAY)thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]# OCR 识别text = pytesseract.image_to_string(thresh, config='--psm 6')all_text.append(text)
# 将识别结果保存为表格text_combined = "\n".join(all_text)lines = [line.split() for line in text_combined.split('\n') if line.strip()]df = pd.DataFrame(lines)if file_ext == '.xlsx':df.to_excel(output_path, index=False, header=False)else:df.to_csv(output_path, index=False, header=False)print(f"OCR 转换完成!结果已保存至: {output_path}")
except Exception as e:print(f"转换失败: {e}")
if __name__ == "__main__":# 命令行参数解析parser = argparse.ArgumentParser(description="PDF 表格提取工具")parser.add_argument("pdf_path", help="输入的 PDF 文件路径")parser.add_argument("output_path", help="输出的 Excel/CSV 文件路径")parser.add_argument("--ocr", action="store_true", help="强制使用 OCR(针对扫描件)")args = parser.parse_args()# 运行转换pdf_to_excel(args.pdf_path, args.output_path, args.ocr)
命令行运行
# 默认自动检测 PDF 类型
python pdf_to_excel.py input.pdf output.xlsx# 强制使用 OCR(针对扫描件)
python pdf_to_excel.py scanned.pdf output.csv --ocr
直接调用函数
pdf_to_excel("input.pdf", "output.xlsx", use_ocr=False)
重点说明:
文本型 PDF:使用 tabula-py 直接提取表格结构。
扫描件/图片 PDF:
通过 pdf2image 将 PDF 转为图片。
使用 OpenCV 对图像预处理(二值化、去噪)。
调用 pytesseract(Tesseract OCR)识别文字并生成表格。
扫描件质量:OCR 精度受图片清晰度影响,建议高分辨率 PDF。
复杂表格:若表格有合并单元格,可能需要手动调整输出结果。
中文支持:确保 Tesseract 安装了中文语言包(chi_sim)。
如果需要进一步优化(如自定义表格解析逻辑),可以在此基础上扩展!