设计目的
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随意右击
- 不定期更新