【python】word转为pdf

设计目的

wps的pdf转换要钱,office的转换格式错误

缺点

1.对于office 的word文件和wps的word文件,存在不同方式的pdf转换,可能出现排版错误(解决方法,多点几次转换,实在不行就不换了)
2.设计界面不人性化(有空改,没空将就用着)

完整代码

前提:引入tkinter、下载了docx2pdf的压缩包

import tkinter as tk
from tkinter import filedialog
from docx2pdf import convert
from tkinter import ttk  # Import the ttk module for the progress bar

def select_input_file():
    input_file = filedialog.askopenfilename(title="选择要转换的Word文档")
    input_file_entry.delete(0, tk.END)
    input_file_entry.insert(tk.END, input_file)

def select_output_file():
    output_file = filedialog.asksaveasfilename(title="选择保存的PDF文件", defaultextension=".pdf")
    output_file_entry.delete(0, tk.END)
    output_file_entry.insert(tk.END, output_file)

def convert_to_pdf():
    input_file = input_file_entry.get()
    output_file = output_file_entry.get()
    
    # Create a progress bar
    progress_bar = ttk.Progressbar(window, orient=tk.HORIZONTAL, length=200, mode='indeterminate')
    progress_bar.pack()
    progress_bar.start()  # Start the progress bar
    
    try:
        convert(input_file, output_file)  # Convert the file
        
        # Conversion completed successfully
        progress_bar.stop()  # Stop the progress bar
        progress_bar.destroy()  # Remove the progress bar widget
        
        result_label.config(text="转换成功!")  # Update the result label
        
    except Exception as e:
        progress_bar.stop()  # Stop the progress bar
        progress_bar.destroy()  # Remove the progress bar widget
        
        result_label.config(text="转换失败:" + str(e))  # Update the result label with the error message

# 创建主窗口
window = tk.Tk()
window.title("Word转PDF工具")

# 创建选择输入文件的按钮和文本框
input_file_label = tk.Label(window, text="选择要转换的Word文档:")
input_file_label.pack()
input_file_entry = tk.Entry(window, width=50)
input_file_entry.pack()
input_file_button = tk.Button(window, text="选择文件", command=select_input_file)
input_file_button.pack()

# 创建选择输出文件的按钮和文本框
output_file_label = tk.Label(window, text="选择保存的PDF文件:")
output_file_label.pack()
output_file_entry = tk.Entry(window, width=50)
output_file_entry.pack()
output_file_button = tk.Button(window, text="选择文件", command=select_output_file)
output_file_button.pack()

# 创建转换按钮
convert_button = tk.Button(window, text="转换为PDF", command=convert_to_pdf)
convert_button.pack()

# 创建结果标签
result_label = tk.Label(window, text="")
result_label.pack()

# 运行主循环
window.mainloop()

使用方式

在vscode随意右击
在这里插入图片描述

  • 不定期更新
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值