python实现pdf转word和excel

一、引言

在办公中,我们经常遇收到pdf文件格式,因为pdf格式文件不易修改,当我们需要编辑这些pdf文件时,经常需要开通会员或收费功能才能使用编辑功能。今天,我要和大家分享的,是如何使用python编程实现,将PDF文件轻松转换成Word和Excel格式,让编辑变得轻而易举。

二、python编程

要将PDF转换为Word,我们需要解析PDF的布局和内容,并将其重新格式化为Word文档。这涉及到复杂的文本识别和格式转换技术。

使用过如下几个库:最好的还是pdf2docx。

(一)、使用 pdf2docx 库

(二)、使用 PyMuPDF 库

(三)、使用 pdfplumber 库

(四)、使用 PyPDF2 和 python-docx 库

重点:pdf2docx 是一个将 PDF 文件转换为 DOCX 文件的 Python 库。

pip install pdf2docx -i https://mirrors.aliyun.com/pypi/simple

更换PIP源

PIP源在国外,速度慢,可以更换为国内源,以下是国内一些常用的PIP源。

豆瓣(douban) http://pypi.douban.com/simple/

清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/

阿里云 http://mirrors.aliyun.com/pypi/simple/

中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

1,PDF转Word

python 复制代码
from pdf2docx import Converter

# pdf转word方法
def pdf_to_word(pdf_path, word_path=None, page_nums=None):
    '''
    @方法名称: pdf转word
    @中文注释: pdf转word
    @入参:
        @param pdf_path str pdf文件路径
        @param page_nums str 页码序号
    @出参:
        @返回状态:
            @return 0 失败或异常
            @return 1 成功
        @返回错误码
        @返回错误信息
        @param doc_file str word文件名
    @作    者: PandaCode辉
    @weixin公众号: PandaCode辉
    @创建时间: 2024-12-17
    @使用范例: pdf_to_word('test.pdf')
    '''
    global cv
    result_dict = {}
    try:
        if not type(pdf_path) is str:
            result_dict["error_code"] = "111111"
            result_dict["error_msg"] = "pdf文件路径参数类型错误,不为字符串"
            return result_dict
        # 检查PDF文件是否存在
        if not os.path.isfile(pdf_path):
            result_dict["error_code"] = "999999"
            result_dict["error_msg"] = f"PDF文件未找到: {pdf_path}"
            return result_dict

        start_time = time.time()

        if not word_path:
            # 使用os.path.basename()获取文件名
            file_path = os.path.dirname(pdf_path)
            # 使用os.path.basename()获取文件名
            file_name = os.path.basename(pdf_path)
            # 提取文件名,去除文件后缀
            file_name = file_name.split('.')[0]
            # print(file_name)
            # word文件名+路径
            word_path = os.path.join(file_path, f'{file_name}.docx')
            # print(word_path)

        # 初始化转换器
        cv = Converter(pdf_path)
        # 转换整本PDF或指定页码
        if page_nums:
            # 解析页码参数
            pages = []
            for part in page_nums.split(','):
                if '-' in part:
                    start, end = part.split('-')
                    pages.extend(range(int(start) - 1, int(end)))
                else:
                    pages.append(int(part) - 1)
            # 转换指定页码
            cv.convert(docx_filename=word_path, pages=pages)
        else:
            # 转换整本PDF
            cv.convert(docx_filename=word_path, start=0)

        # 保存为Word文档
        cv.close()

        # 识别时间
        end_time = time.time()
        # 计算耗时差,单位毫秒
        recognize_time = (end_time - start_time) * 1000
        # 保留2位小数
        recognize_time = round(recognize_time, 2)
        # print('处理时间:' + str(recognize_time) + '毫秒')
        result_dict["recognize_time"] = recognize_time
        result_dict["error_code"] = "000000"
        result_dict["error_msg"] = "pdf转word成功"
        # 使用os.path.basename()获取文件名
        word_file_name = os.path.basename(word_path)
        # 打印结果
        # print("文件名:", word_file_name)
        result_dict["filename"] = word_file_name

        result_dict["file_size_mb"] = file_size_mb

        return result_dict

    except Exception as e:
        cv.close()
        print("pdf转word异常," + str(e))
        result_dict["error_code"] = "999999"
        result_dict["error_msg"] = "PDF到Word转换过程中发生错误," + str(e)
        return result_dict

2,PDF转Excel

要将PDF转换为Excel,目前没有现成的转换库,需要稍加处理下。

使用过如下几个库:

(一)、使用 pdf2docx 库 和 docx 库 和 pandas 库

先将pdf转成word文档,然后读取word文档中的表格内容,然后再转成excel文档。

pip install python-docx -i https://mirrors.aliyun.com/pypi/simple

pip install pandas -i https://mirrors.aliyun.com/pypi/simple

python 复制代码
from docx import Document
import pandas as pd
'''
不擅长编程的用户,可以选择我的免费工具箱,开箱即用,方便快捷。
print("搜/索/wei/xin/小/程/序:  全能科技工具箱")
'''
# pdf转excel方法
def pdf_to_excel(pdf_path, xlsx_path=None, page_nums=None):
    '''
    @方法名称: pdf转excel
    @中文注释: pdf转excel
    @入参:
        @param pdf_path str pdf文件路径
        @param page_nums str 页码序号
    @出参:
        @返回状态:
            @return 0 失败或异常
            @return 1 成功
        @返回错误码
        @返回错误信息
        @param xlsx_file str excel文件名
    @作    者: PandaCode辉
    @weixin公众号: PandaCode辉
    @创建时间: 2025-01-06
    @使用范例: pdf_to_excel('test.pdf')
    '''
    global cv
    result_dict = {}
    try:
        if not type(pdf_path) is str:
            result_dict["error_code"] = "111111"
            result_dict["error_msg"] = "pdf文件路径参数类型错误,不为字符串"
            return result_dict
        # 检查PDF文件是否存在
        if not os.path.isfile(pdf_path):
            result_dict["error_code"] = "999999"
            result_dict["error_msg"] = f"PDF文件未找到: {pdf_path}"
            return result_dict

        start_time = time.time()

        # 使用os.path.basename()获取文件名
        file_path = os.path.dirname(pdf_path)
        # 使用os.path.basename()获取文件名
        file_name = os.path.basename(pdf_path)
        # 提取文件名,去除文件后缀
        file_name = file_name.split('.')[0]
        # print(file_name)
        # word文件名+路径
        word_path = os.path.join(file_path, f'{file_name}.docx')
        # print(word_path)
        if not xlsx_path:
            # xlsx文件名+路径
            xlsx_path = os.path.join(file_path, f'{file_name}.xlsx')
            # print(xlsx_path)

        # 第一步,先将pdf转成doc文档
        rsp_dict = pdf_to_word(pdf_path, page_nums=page_nums)
        if rsp_dict["error_code"] == "000000":
            # 第二步,再读取doc文档,转成xlsx文档
            # 打开Word文档
            doc = Document(word_path)

            if len(doc.tables) < 1:
                result_dict["error_code"] = "999999"
                result_dict["error_msg"] = "PDF文件未找到表格内容,无法转成xlsx文档."
                return result_dict

            # 创建一个Excel writer对象
            with pd.ExcelWriter(xlsx_path, engine='openpyxl') as writer:

                # 遍历文档中的所有表格
                for i, table in enumerate(doc.tables, start=1):
                    # 创建一个空的DataFrame来存储表格数据
                    data = []

                    # 遍历表格中的所有行
                    for row in table.rows:
                        # 遍历行中的所有单元格
                        row_data = []
                        for cell in row.cells:
                            row_data.append(cell.text)
                        data.append(row_data)

                    # 将数据转换为DataFrame
                    df = pd.DataFrame(data)

                    # 将DataFrame保存到Excel的不同工作表中
                    sheet_name = f"Table_{i}"
                    df.to_excel(writer, sheet_name=sheet_name, index=False, header=False)

            # print(f"转换完成,结果保存在{xlsx_path}中。")
        else:
            result_dict["error_code"] = rsp_dict["error_code"]
            result_dict["error_msg"] = rsp_dict["error_msg"]
            return result_dict

        # 识别时间
        end_time = time.time()
        # 计算耗时差,单位毫秒
        recognize_time = (end_time - start_time) * 1000
        # 保留2位小数
        recognize_time = round(recognize_time, 2)
        # print('处理时间:' + str(recognize_time) + '毫秒')
        result_dict["recognize_time"] = recognize_time
        result_dict["error_code"] = "000000"
        result_dict["error_msg"] = "pdf转excel成功"
        # 使用os.path.basename()获取文件名
        xlsx_file_name = os.path.basename(xlsx_path)
        result_dict["filename"] = xlsx_file_name

        return result_dict

    except Exception as e:
        print("pdf转excel异常," + str(e))
        result_dict["error_code"] = "999999"
        result_dict["error_msg"] = "PDF到excel转换过程中发生错误," + str(e)
        return result_dict

(二)、使用 pdfplumber 和 python-pandas 库

使用pdfplumber库读取pdf表格内容,然后写入excel表格文档中。

pip install pdfplumber -i https://mirrors.aliyun.com/pypi/simple

python 复制代码
import pandas as pd
import pdfplumber

'''
不擅长编程的用户,可以选择我的免费工具箱,开箱即用,方便快捷。
print("搜/索/wei/xin/小/程/序:  全能科技工具箱")
'''

def pdf_to_excel_new(pdf_path, xlsx_path=None, page_nums=None):
    '''
    @方法名称: pdf转excel
    @中文注释: pdf转excel
    @入参:
        @param pdf_path str pdf文件路径
        @param page_nums str 页码序号
    @出参:
        @返回状态:
            @return 0 失败或异常
            @return 1 成功
        @返回错误码
        @返回错误信息
        @param xlsx_file str excel文件名
    @作    者: PandaCode辉
    @weixin公众号: PandaCode辉
    @创建时间: 2025-01-06
    @使用范例: pdf_to_excel('test.pdf')
    '''
    result_dict = {}
    try:
        if not type(pdf_path) is str:
            result_dict["error_code"] = "111111"
            result_dict["error_msg"] = "pdf文件路径参数类型错误,不为字符串"
            return result_dict
        # 检查PDF文件是否存在
        if not os.path.isfile(pdf_path):
            result_dict["error_code"] = "999999"
            result_dict["error_msg"] = f"PDF文件未找到: {pdf_path}"
            return result_dict

        start_time = time.time()

        # 使用os.path.basename()获取文件名
        file_path = os.path.dirname(pdf_path)
        # 使用os.path.basename()获取文件名
        file_name = os.path.basename(pdf_path)
        # 提取文件名,去除文件后缀
        file_name = file_name.split('.')[0]
        # print(file_name)

        if not xlsx_path:
            # xlsx文件名+路径
            xlsx_path = os.path.join(file_path, f'{file_name}.xlsx')
            # print(xlsx_path)

        # 提取 PDF 中的文本数据
        with pdfplumber.open(pdf_path) as pdf:
            if len(pdf.pages) < 1:
                result_dict["error_code"] = "999999"
                result_dict["error_msg"] = "PDF文件未找到表格内容,无法转成xlsx文档."
                return result_dict

            # 创建一个 Excel 的写入器
            with pd.ExcelWriter(xlsx_path) as writer:
                # 转换整本PDF或指定页码
                if page_nums:
                    # 解析页码参数
                    pages = []
                    for part in page_nums.split(','):
                        if '-' in part:
                            start, end = part.split('-')
                            pages.extend(range(int(start) - 1, int(end)))
                        else:
                            pages.append(int(part) - 1)
                    # 转换指定页码
                    for i in pages:
                        page = pdf.pages[i]
                        # 提取当前页的表格数据
                        table = page.extract_table()
                        if table:
                            # 将表格数据转换为 DataFrame
                            df = pd.DataFrame(table)
                            # 将 DataFrame 写入 Excel 的不同工作表
                            df.to_excel(writer, sheet_name=f'Page {i}', index=False)
                else:
                    # 转换整本PDF
                    for i, page in enumerate(pdf.pages, start=1):
                        # 提取当前页的表格数据
                        table = page.extract_table()
                        if table:
                            # 将表格数据转换为 DataFrame
                            df = pd.DataFrame(table)
                            # 将 DataFrame 写入 Excel 的不同工作表
                            df.to_excel(writer, sheet_name=f'Page {i}', index=False)

        # 识别时间
        end_time = time.time()
        # 计算耗时差,单位毫秒
        recognize_time = (end_time - start_time) * 1000
        # 保留2位小数
        recognize_time = round(recognize_time, 2)
        # print('处理时间:' + str(recognize_time) + '毫秒')
        result_dict["recognize_time"] = recognize_time
        result_dict["error_code"] = "000000"
        result_dict["error_msg"] = "pdf转excel成功"
        # 使用os.path.basename()获取文件名
        xlsx_file_name = os.path.basename(xlsx_path)
        # 打印结果
        # print("文件名:", xlsx_file_name)
        result_dict["filename"] = xlsx_file_name

        # 获取文件大小(字节)
        file_size_bytes = os.path.getsize(xlsx_path)
        # 将字节转换为兆字节
        file_size_mb = file_size_bytes / (1024 * 1024)
        # 打印结果
        # print("文件大小(兆字节):", file_size_mb)
        result_dict["file_size_mb"] = file_size_mb
        return result_dict

    except Exception as e:
        print("pdf转excel异常," + str(e))
        result_dict["error_code"] = "999999"
        result_dict["error_msg"] = "PDF到excel转换过程中发生错误," + str(e)
        return result_dict

三、前端页面效果展示

1,选择PDF文件

2,选择转换类型:PDF转Word 和 PDF转Excel

3,页面范围:可选参数,不选则全部转换

总结

  • pdf2docxPyMuPDF 是pdf转word更直接的选择,因为它们专门用于转换 PDF 到 DOCX,并且通常在版面还原方面做得更好。
  • pdfplumber 更适合于文本和表格的提取,而不是直接的格式转换。
  • PyPDF2python-docx 的组合提供了更多的灵活性,但可能需要更多的自定义代码来处理复杂的布局和格式。

根据你的需求,选择最适合你的库。如果你需要高度保真的版面还原,pdf2docxPyMuPDF 可能是更好的选择。如果你需要从 PDF 中提取文本和表格数据,pdfplumber 可能更适合。

相关推荐
傻啦嘿哟3 小时前
Python 操作 Excel 条件格式指南
开发语言·python·excel
热爱生活的五柒4 小时前
word中如何一键修改英文字母数字为新罗马字体Times New Roman
word·西文·times new roman
jgyzl8 小时前
2026.3.20 用EasyExcel实现excel报表的导入与导出
java·python·excel
葡萄城技术团队9 小时前
SpreadJS 中“打印”和“导出 PDF”到底该选哪个?
pdf
优化控制仿真模型10 小时前
2025年12月英语六级真题及答案解析完整版(第一、二、三套全PDF)
经验分享·pdf
芒果大胖砸10 小时前
uniapp 在h5中预览pdf hybrid方法
pdf·uni-app
大傻^10 小时前
Spring AI Alibaba 文档智能处理:PDF、Markdown知识入库全链路
java·人工智能·spring·pdf·知识图谱·springai·springaialibaba
伟贤AI之路11 小时前
Markdown写彩色文字+公式,MD2WD直接转Word,保留所有格式
word·markdown
bu_shuo11 小时前
Mathtype的公式在word中显示不全的问题
word·学位论文·mathtype·论文格式
zzh9407713 小时前
2026年AI文件上传功能实战:聚合站处理图片、PDF、PPT全指南
人工智能·pdf·powerpoint