LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

用Python将 PDF 中的表格提取为 Excel/CSV(附源代码)

admin
2025年8月28日 1:50 本文热度 98

*用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}")
                return

            except 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)。

如果需要进一步优化(如自定义表格解析逻辑),可以在此基础上扩展!


阅读原文:原文链接


该文章在 2025/8/28 15:44:50 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved