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,页面范围:可选参数,不选则全部转换

  

总结

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

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

相关推荐
用户298698530143 小时前
React 前端实现 Excel 与 HTML 双向转换:基于 WebAssembly 的浏览器端方案
javascript·html·excel
开开心心就好3 小时前
显示器关不掉怎么办,用小工具一键息屏
算法·智能手机·pdf·计算机外设·ocr·lua·1024程序员节
weixin_537217063 小时前
2027年袁东申论万能素材(PDF)
经验分享·pdf
用户0332126663671 天前
使用 Python 轻松移除 Excel 文档中的重复行
python·excel
AI英德西牛仔1 天前
智谱清言导出word指令失效?PC端深度用户正在用“AI导出鸭”重构内容归档流
人工智能·重构·word·excel·deepseek·ai导出鸭
开开心心就好2 天前
PDF水印怎么去掉?勾选对象再点匹配
java·前端·mysql·支持向量机·pdf·音视频·模拟退火算法
用户0332126663672 天前
使用 Python 删除 Excel 中的空白行或空白列
python·excel
开开心心就好3 天前
两张表格数据对比工具,不用写函数也能查
算法·spring·智能手机·pdf·电脑·intellij-idea·音视频
AI导出鸭PC端3 天前
用 AI 导出鸭高效处理:豆包导 pdf 怎么压缩但清晰
android·人工智能·pdf·豆包·ai导出鸭
木头左3 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化