如何在Python中将PDF转换为Docx?代码实现示例

2021年11月17日03:37:39 发表评论 1,001 次浏览

本文带你了解如何使用 pdf2docx 库在 Python 中将 PDF 文件转换为 docx word 文件。

Python如何将PDF转换为Docx?在本教程中,我们将深入探讨如何使用pdf2docx库将 PDF 文件转换为 docx 扩展名。

本教程的目标是开发一个轻量级的基于命令行的实用程序,通过基于 Python 的模块,而不依赖于 Python 生态系统之外的外部实用程序,以便转换位于文件夹中的一个或一组 PDF 文件。

如何在Python中将PDF转换为Docx?pdf2docx是一个 Python 库,可以使用PyMuPDF从 PDF 中提取数据,使用规则解析布局,并使用python-docx生成 docx 文件。python-docx是pdf2docx用于创建和更新 Microsoft Word (.docx) 文件的另一个库。

下面是完整的Python将PDF转换为Docx示例和代码:

进入要求:

$ pip install pdf2docx==0.5.1

让我们从导入模块开始:

# Import Libraries
from pdf2docx import parse
from typing import Tuple

让我们定义负责将 PDF 转换为 Docx 的函数:

def convert_pdf2docx(input_file: str, output_file: str, pages: Tuple = None):
    """Converts pdf to docx"""
    if pages:
        pages = [int(i) for i in list(pages) if i.isnumeric()]
    result = parse(pdf_file=input_file,
                   docx_with_path=output_file, pages=pages)
    summary = {
        "File": input_file, "Pages": str(pages), "Output File": output_file
    }
    # Printing Summary
    print("## Summary ########################################################")
    print("\n".join("{}:{}".format(i, j) for i, j in summary.items()))
    print("###################################################################")
    return result

convert_pdf2docx()功能允许你指定要转换的页面范围,它将 PDF 文件转换为 Docx 文件并最终打印转换过程的摘要。

现在让我们使用它:

if __name__ == "__main__":
    import sys
    input_file = sys.argv[1]
    output_file = sys.argv[2]
    convert_pdf2docx(input_file, output_file)

Python如何将PDF转换为Docx?我们只是使用 Python 的内置 sys 模块从命令行参数中获取输入和输出文件名。让我们尝试一个Python将PDF转换为Docx示例在此处获取):

$ python convert_pdf2docx.py letter.pdf letter.docx

letter.docx当前目录下会出现一个新文件,输出如下:

Parsing Page 1: 1/1...
Creating Page 1: 1/1...
--------------------------------------------------
Terminated in 0.10869679999999998s.
## Summary ########################################################
File:letter.pdf
Pages:None
Output File:letter.docx
###################################################################

你还可以在convert_pdf2docx()函数中指定所需的页面。

如何在Python中将PDF转换为Docx?我希望你喜欢这个简短的教程,并且你发现这个转换器很有用。

PDF相关教程:

  • 如何在 Python 中为 PDF 文件加水印。
  • 如何使用 Python 突出显示和编辑 PDF 文件中的文本。
  • 如何在 Python 中从 PDF 中提取图像。
  • 如何在 Python 中提取所有 PDF 链接。
  • 如何在 Python 中从 PDF 中提取表格。
  • 如何使用 Python 从 PDF 文件中的图像中提取文本。
木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: