领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

Python 开发Word转PDF工具实现

nixiaole 2025-01-02 18:14:24 知识剖析 30 ℃

用Python的win32库和tkinter库实现将Word文档转换为PDF文件,并实现一个简单的图形界面的示例代码,同时也可以将其打包成可执行文件(exe文件)。

代码示例

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import tkinter
from tkinter import ttk, filedialog, messagebox
from win32com.client import constants, gencache, Dispatch

# 初始化窗口大小
window_width = 650
window_height = 330
# 程序主窗口
tk = tkinter.Tk()

# 程序窗口标题
tk.title('WordToPDF V1.0')

# 获取当前屏幕的大小
screen_width, screen_height = tk.maxsize()

# 设置程序居中的 x轴 和 y轴,并用int取整
center_x = int((screen_width - window_width) / 2)
center_y = int((screen_height - window_height) / 2)

# 格式化窗口参数
size_xy = '{0}x{1}+{2}+{3}'.format(window_width, window_height, center_x, center_y)

# 设置程序窗口大小及位置
tk.geometry(size_xy)

# 禁止修改窗口大小
tk.resizable(False, False)

# 创建frame容器并设置大小
frame = tkinter.Frame(tk)
frame.place(x=1, y=5, width=650, height=280)

scrollBar = tkinter.Scrollbar(frame)
scrollBar.pack(side=tkinter.RIGHT, fill=tkinter.Y)

# 初始化表格,并定义列, show='headings' 隐藏第一列
tree = tkinter.ttk.Treeview(frame, columns=['序号', '文件名', '文件大小(M)'], show='headings', yscrollcommand=scrollBar.set)

# 设置列宽,及文字方向
tree.column('序号', width=49, anchor='center')
tree.column('文件名', width=480, anchor='center')
tree.column('文件大小(M)', width=100, anchor='center')

# 设置窗口中显示的列名
tree.heading('序号', text='序号')
tree.heading('文件名', text='文件名')
tree.heading('文件大小(M)', text='文件大小(M)')

FILE_LIST = list()

def open_file():
    # 打开文件,并指定文件类型
    ret = filedialog.askopenfilenames(filetypes=[('word', ('.doc', '.docx'))])
    global FILE_LIST
    number = len(FILE_LIST) + 1
    for i in ret:
        file_name = os.path.basename(i)
        file_size = round(os.path.getsize(i) / 1024 / 1024, 2)
        # 转换路径
        file_path = os.path.abspath(i)
        # 判断是否重复上传
        if file_path in FILE_LIST:
            tkinter.messagebox.showinfo('提示', '请勿重复上传')
        else:
            tree.insert('', 0, value=[number, file_name, file_size])
            number += 1
            FILE_LIST.append(file_path)


def start_conversion():
    if FILE_LIST:
        # tkinter.messagebox.showinfo('提示', '正在转换请稍后')
        # pdf_file_path = os.path.abspath(os.path.dirname(__file__)) + '\\pdf_file\\'
        pdf_file_path = os.path.expanduser('~') + '\\Desktop\\'     # 默认保存桌面
        # 如果 pdf_file 文件夹不在则创建
        if not os.path.exists(pdf_file_path):
            os.mkdir(pdf_file_path)

        for word_path in FILE_LIST:
            print(FILE_LIST)
            print('word_path=', word_path)
            # 截取文件名
            file_name = os.path.basename(word_path).split('.')[0]
            # 拼接保存pdf路径
            pdf_path = pdf_file_path + file_name + '.pdf'
            print((pdf_path))
            # 成成pdf文件
            # word = gencache.EnsureDispatch("Word.Application")
            word = Dispatch('Word.Application')
            doc = word.Documents.Open(word_path, ReadOnly=1)
            doc.SaveAs(pdf_path, FileFormat=17)
            doc.Close()
            # word.Quit(constants.wdDoNotSaveChanges)
        tkinter.messagebox.showinfo('提示', '转换完成')
        # 转换完成后清空tree下的内容
        tc = tree.get_children()
        for item in tc:
            tree.delete(item)
        # 转换完成后清空文件列表
        del FILE_LIST[:]
    else:
        tkinter.messagebox.showinfo('提示', '全部转换完成或列表中没有内容')
# 创建按钮
btn_add = tkinter.Button(tk, text='添加文件', command=open_file)
btn_start = tkinter.Button(tk, text='开始转换', command=start_conversion)

# btn标签位置
btn_add.place(x=1, y=290)
btn_start.place(x=70, y=290)
tree.pack(side=tkinter.LEFT, fill=tkinter.Y)

# #Treeview组件与垂直滚动条结合
scrollBar.config(command=tree.yview)

# 主窗口显示
tk.mainloop()

安装pyinstaller

打包exe文件,cmd进入py文件所在路径执行以下命令

pyinstaller -w -F Word2PDF.py
pyinstaller参数说明:

-h    显示帮助信息
-v    显示版本号
–distpath    指定打包后的程序存放目录,默认存放在当前目录下的dist目录
–workpath    为输出的所有临时文件指定存放目录
-c    显示命令行窗口
-w    不显示命令行窗口
-D    生成结果是一个包含exe程序的目录,所有第三方依赖库和其他资源和exe程序位于同一目录下
-F    生成结果是一个exe程序,所有第三方依赖库和其他资源都被打包进该exe程序中
-i    为生成的程序指定一个icon图标
-n    指定生成的.exe和.spec文件名
最近发表
标签列表