结构与功能
- 初始化和GUI设置:
PdfConverter
类初始化应用程序,设置主窗口和用户界面元素。包括用于选择单个文件或文件夹的按钮,以及将PDF转换为JPG图片或Word文档的选项。 - 文件和文件夹选择:
single_folder()
:打开一个对话框选择文件夹,列出其中所有的PDF文件。multiple_files()
:打开一个对话框选择多个PDF文件,支持跨不同目录选择文件。
- 转换功能:
pdf_to_jpg()
:将选定的PDF文件转换为JPG图片,将每一页保存为一张图片。使用PyMuPDF(fitz)打开PDF文件并提取图片。pdf_to_word()
:使用pdf2docx转换器将选定的PDF文件转换为Word(.docx)格式。每个PDF被转换为一个与原始PDF文件同名的Word文档。
- 转换过程中使用线程:转换功能通过分别在不同的线程(
threading.Thread
)中执行,以防止在转换过程中GUI冻结。这种方式允许应用程序在显示转换进度和完成消息的同时保持响应。 - 隐藏控制台窗口:脚本检查是否存在控制台窗口(
ctypes.windll.kernel32.GetConsoleWindow()
),并将其隐藏,为用户提供更清洁的应用程序界面。这在将脚本打包成可分发的执行文件时特别有用。
执行流程
- 应用程序通过实例化
PdfConverter
类启动。 - 用户选择要转换的PDF文件或包含PDF文件的文件夹。
- 在选择了转换方法(转换为JPG或Word)后,应用程序在一个单独的线程中开始转换过程。
- 转换进度和完成消息显示在GUI的文本区域中。
- 转换后的文件保存在原始PDF相同的目录中(对于JPG,将创建一个以PDF文件名命名的新文件夹)。
关键库
- Tkinter:用于创建图形用户界面。
- PyMuPDF(fitz):提供处理PDF文件的功能,包括读取PDF和提取图像。
- pdf2docx:一个专门用于将PDF文件转换成Word文档的库。
- ctypes:Python的外部函数库,用于与Windows进程和GUI元素交互,特别是用于隐藏控制台窗口。
功能说明
1、将PDF文件转换为JPG图片;
2、将PDF文件转换为Word文档,若PDF文件是通过Word文档转换的,可完美转换为可编辑Word文档。
3、可选择多个文件或文件夹批量转换。
需要安装第三方库:
pdf2docx==0.5.7
PyMuPDF==1.23.8
源码
import tkinter as tk
from tkinter import filedialog
import fitz
from pdf2docx import Converter
import os
import time
import threading
import ctypes
class PdfConverter:
def __init__(self):
self.root = tk.Tk()
self.root.title('PDF转换器')
self.root.geometry("500x300+350+250")
#self.root.resizable(width=False,height=False)禁用最大化
#self.root.overrideredirect(1)删除主窗口标题栏
self.interface()
def interface(self):
""""界面编写位置"""
self.Button0 = tk.Button(self.root, text="选择文件", command=self.multiple_files)
self.Button0.grid(row=0, column=0, pady=20)
self.Button0 = tk.Button(self.root, text="选择文件夹", command=self.single_folder)
self.Button0.grid(row=0, column=1, pady=20)
self.Button1 = tk.Button(self.root, text="转为图片", command=self.start_to_jpg)
self.Button1.grid(row=0, column=2, pady=20)
self.Button2 = tk.Button(self.root, text="转为Word", command=self.start_to_word)
self.Button2.grid(row=0, column=3, pady=20)
self.w1 = tk.Text(self.root, width=68, height=15)
self.w1.insert('insert','说明:1、文件可单选或多选;文件夹下文件均需转换,可直接选择文件夹;\n 2、转换后文件保存位置为所选文件或文件夹位置。')
self.w1.grid(row=1, column=0, columnspan=4, padx=10)
def single_folder(self):
'''获取单个文件夹'''
path = filedialog.askdirectory() + '/'
files_path = [os.path.join(path,i) for i in os.listdir(path) if os.path.splitext(i)[-1].lower() == '.pdf']
if len(files_path) != 0:
self.w1.delete('1.0',tk.END)
self.w1.insert('insert','\n'.join(files_path))
def multiple_files(self):
'''获取多个文件'''
path = filedialog.askopenfilenames(filetypes=[('All Files', '.PDF')])
if len(path) != 0:
self.w1.delete('1.0',tk.END)
self.w1.insert('insert','\n'.join(path))
def pdf_to_jpg(self):
'''将PDF转换为图片'''
start_time = time.time()
for file in self.path_list:
os.makedirs(os.path.splitext(file)[0],exist_ok=True) # 创建以PDF文件名命名的文件夹
pdf = fitz.open(file) # 打开PDF文件
temp = 0
for pg in range(pdf.page_count):
page = pdf[pg]
temp += 1
rotate = int(0)
# 每个尺寸的缩放系数为2,这将为我们生成分辨率提高四倍的图像。
zoom_x = 2
zoom_y = 2
trans = fitz.Matrix(zoom_x, zoom_y).prerotate(rotate)
pm = page.get_pixmap(matrix=trans, alpha=False)
pic_name = '{}.jpg'.format(temp)
#拼接生成图片存放的文件路径
pic_pwd = os.path.join(os.path.splitext(file)[0], pic_name)
pm.save(pic_pwd)
self.w1.insert('end','完成 %s 转换\n' % os.path.split(file)[1])
#self.w1.insert(tk.INSERT,'\n')换行
end_time = time.time()
self.w1.insert('end','转换已完成,共用时 %.2f 秒' % ((end_time - start_time)))
def start_to_jpg(self):
#将路径字符串转换为列表,strip():去除字符串前后空格或特殊字符;split('\n'):将字符串转为列表,元素以换行符分割
self.path_list = self.w1.get('1.0','end').strip().split('\n')
self.w1.delete('1.0',tk.END)
if os.path.isfile(self.path_list[0]):
self.T = threading.Thread(target=self.pdf_to_jpg)
self.T.setDaemon(True)
self.T.start()
else:
self.w1.insert('insert','请选择文件或文件夹')
def pdf_to_word(self):
'''将PDF转换为WORD'''
start_time = time.time()
for file in self.path_list:
docx_name = os.path.splitext(file)[0] + '.docx'
cv = Converter(file)
cv.convert(docx_name)
cv.close
self.w1.insert('end','完成 %s 转换\n' % os.path.split(file)[1])
#self.w1.insert(tk.INSERT,'\n')换行
end_time = time.time()
self.w1.insert('end','转换已完成,共用时 %.2f 秒' % ((end_time - start_time)))
def start_to_word(self):
#将路径字符串转换为列表,strip():去除字符串前后空格或特殊字符;split('\n'):将字符串转为列表,元素以换行符分割
self.path_list = self.w1.get('1.0','end').strip().split('\n')
self.w1.delete('1.0',tk.END)
if os.path.isfile(self.path_list[0]):
self.T = threading.Thread(target=self.pdf_to_word)
self.T.setDaemon(True)
self.T.start()
else:
self.w1.insert('insert','请选择文件或文件夹')
if __name__ == '__main__':
whnd = ctypes.windll.kernel32.GetConsoleWindow()
if whnd != 0:
ctypes.windll.user32.ShowWindow(whnd, 0)
ctypes.windll.kernel32.CloseHandle(whnd)
a = PdfConverter()
#a.root.after(1000,a.pdf_to_jpg)
a.root.mainloop()