Python实现PDF转Word的方法详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python实现PDF转Word的方法详解

Sir 老王   2023-03-21 我要评论

由于PDF的文件大多都是只读文件,有时候为了满足可以编辑的需要通常可以将PDF文件直接转换成Word文件进行操作。

看了网络上面的python转换PDF文件为Word的相关文章感觉都比较复杂,并且关于一些图表的使用还要进行特殊的处理。

本篇文章主要讲解关于如何使用python是实现将PDF转换成Word的业务过程,这次没有使用GUI应用的操作。

由于可能存在版本冲突的问题,这里将开发过程中需要使用的python非标准库的版本列举出来。

  • python内核版本:3.6.8
  • PyMuPDF版本:1.18.17
  • pdf2docx版本:0.5.1

可以选择pip的方式对使用到的python非标准库进行安装。

pip install PyMuPDF==1.18.17

pip install pdf2docx==0.5.1

完成上述的python依赖库安装以后,将pdf2docx导入到我们的代码块中。

# Importing the Converter class from the pdf2docx module.
from pdf2docx import Converter

然后,编写业务函数的代码块,新建一个pdfToWord函数来处理转换逻辑,主要就几行代码可以实现比较简单。

def pdfToWord(pdf_file_path=None, word_file_path=None):
    """
    It takes a pdf file path and a word file path as input, and converts the pdf file to a word file.

    :param pdf_file_path: The path to the PDF file you want to convert
    :param word_file_path: The path to the word file that you want to create
    """
    # Creating a Converter object.
    converter_ = Converter(pdf_file_path)
    # The `convert` method takes the path to the word file that you want to create, and the start and end pages of the PDF
    # file that you want to convert.
    converter_.convert(word_file_path, start=0, end=None)
    converter_.close()

最后,使用main函数调用pdfToWord函数可以直接完成文档格式的转换。

# A special variable in Python that evaluates to `True` if the module is being run directly by the Python interpreter, and
# `False` if it has been imported by another module.
if __name__ == '__main__':
    pdfToWord('D:/test-data-work/test_pdf.pdf', 'D:/test-data-work/test_pdf.docx')

# Parsing Page 2: 2/5...Ignore Line "∑" due to overlap
# Ignore Line "∑" due to overlap
# Ignore Line "ç" due to overlap
# Ignore Line "A" due to overlap
# Ignore Line "i =1" due to overlap
# Ignore Line "æ" due to overlap
# Parsing Page 5: 5/5...
# Creating Page 5: 5/5...
# --------------------------------------------------
# Terminated in 3.2503201s.

方法补充

除了上面的方法,小编还为大家准备了其他方法,需要的小伙伴可以了解一下

方法一:

from pdf2docx import Converter
import PySimpleGUI as sg
 
 
def pdf2word(file_path):
    file_name = file_path.split('.')[0]
    doc_file = f'{file_name}.docx'
    p2w = Converter(file_path)
    p2w.convert(doc_file, start=0, end=None)
    p2w.close()
    return doc_file
 
 
def main():
    # 选择主题
    sg.theme('DarkAmber')
 
    layout = [
        [sg.Text('pdfToword', font=('微软雅黑', 12)),
         sg.Text('', key='filename', size=(50, 1), font=('微软雅黑', 10))],
        [sg.Output(size=(80, 10), font=('微软雅黑', 10))],
        [sg.FilesBrowse('选择文件', key='file', target='filename'), sg.Button('开始转换'), sg.Button('退出')]]
    # 创建窗口
    window = sg.Window("张卧虎", layout, font=("微软雅黑", 15), default_element_size=(50, 1))
    # 事件循环
    while True:
        # 窗口的读取,有两个返回值(1.事件;2.值)
        event, values = window.read()
        print(event, values)
 
        if event == "开始转换":
 
            if values['file'] and values['file'].split('.')[1] == 'pdf':
                filename = pdf2word(values['file'])
                print('文件个数 :1')
                print('\n' + '转换成功!' + '\n')
                print('文件保存位置:', filename)
            elif values['file'] and values['file'].split(';')[0].split('.')[1] == 'pdf':
                print('文件个数 :{}'.format(len(values['file'].split(';'))))
                for f in values['file'].split(';'):
                    filename = pdf2word(f)
                    print('\n' + '转换成功!' + '\n')
                    print('文件保存位置:', filename)
            else:
                print('请选择pdf格式的文件哦!')
        if event in (None, '退出'):
            break
 
    window.close()
main()

方法二:

加密过的PDF转word

#-*- coding: UTF-8 -*- 
#!/usr/bin/python
#-*- coding: utf-8 -*-
import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser,PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import *
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
import os
#设置工作目录文件夹
os.chdir(r'c:/users/dicey/desktop/codes/pdf-docx')
#解析pdf文件函数
def parse(pdf_path):
 fp = open('diya.pdf', 'rb') # 以二进制读模式打开
 # 用文件对象来创建一个pdf文档分析器
 parser = PDFParser(fp)
 # 创建一个PDF文档
 doc = PDFDocument()
 # 连接分析器 与文档对象
 parser.set_document(doc)
 doc.set_parser(parser)
 # 提供初始化密码
 # 如果没有密码 就创建一个空的字符串
 doc.initialize()
 # 检测文档是否提供txt转换,不提供就忽略
 if not doc.is_extractable:
  raise PDFTextExtractionNotAllowed
 else:
  # 创建PDf 资源管理器 来管理共享资源
  rsrcmgr = PDFResourceManager()
  # 创建一个PDF设备对象
  laparams = LAParams()
  device = PDFPageAggregator(rsrcmgr, laparams=laparams)
  # 创建一个PDF解释器对象
  interpreter = PDFPageInterpreter(rsrcmgr, device)
  # 用来计数页面,图片,曲线,figure,水平文本框等对象的数量
  num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0
  # 循环遍历列表,每次处理一个page的内容
  for page in doc.get_pages(): # doc.get_pages() 获取page列表
   num_page += 1 # 页面增一
   interpreter.process_page(page)
   # 接受该页面的LTPage对象
   layout = device.get_result()
   for x in layout:
    if isinstance(x,LTImage): # 图片对象
     num_image += 1
    if isinstance(x,LTCurve): # 曲线对象
     num_curve += 1
    if isinstance(x,LTFigure): # figure对象
     num_figure += 1
    if isinstance(x, LTTextBoxHorizontal): # 获取文本内容
     num_TextBoxHorizontal += 1 # 水平文本框对象增一
     # 保存文本内容
     with open(r'test2.doc', 'a',encoding='utf-8') as f: #生成doc文件的文件名及路径
      results = x.get_text()
      f.write(results)
      f.write('\n')
  print('对象数量:\n','页面数:%s\n'%num_page,'图片数:%s\n'%num_image,'曲线数:%s\n'%num_curve,'水平文本框:%s\n'
    %num_TextBoxHorizontal)

if __name__ == '__main__':
 pdf_path = r'diya.pdf' #pdf文件路径及文件名
 parse(pdf_path)

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们