第一步:安装包
pip install pdf2docx
第二步:敲代码
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 18 21:51:30 2024
把当前目录下所有PDF文件转换成WORD,并保存到当前目录下的\DOC目录中
@author: hjf
"""
import os
import tkinter as tk
from tkinter import filedialog
from pdf2docx import Converter
def pdf_to_word(pdf_file, word_file):
cv = Converter(pdf_file)
cv.convert(word_file,start=0,end=None)
cv.close()
def traverse_pdf_file_dir(directory):
os.walk(directory)
if not os.path.exists("doc"):#准备存放目录,如果不存在就创建它
print("目录 doc 不存在。创建doc 目录")
os.mkdir("doc")
else:
print("目录 doc 已存在。无需创建")
for root, dirs, files in os.walk(directory):
for file in files:
# 检查文件扩展名是否为'.pdf'
if file.endswith('.pdf'):
file_path = os.path.join(root, file)
# 准备存放文件名
excel_file = os.path.dirname(file_path)
excel_file = excel_file + "\doc\\"+os.path.basename(file_path)
excel_file = os.path.splitext(excel_file)#分割文件主名和扩展名
excel_file = excel_file[0]+".docx" #列表第一个元素存放主名
print(file_path)
print(excel_file)
# 调用函数将 PDF 文件转换为 word 文件
# 将转换后的word文件放到‘doc’目录下
pdf_to_word(file_path, excel_file)
# 指定要遍历的目录路径
directory_path = os.getcwd()
traverse_pdf_file_dir(directory_path)
第三步:运行