核心代码
# TODO 编写pdf转换器 制作exe程序
import easygui
import os
from docx2pdf import convert
from pdf2docx import Converter
from pdf2image import convert_from_path
import io
import sys
buffer = io.StringIO()
sys.stdout = buffer
sys.stderr = buffer
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
# TODO word转换成pdf实测可用
def word_to_pdf():
word_file = easygui.fileopenbox(title="请上传要转换为pdf格式的word文件", default="*.docx")
if word_file:
pdf_file = word_file.replace(".docx", ".pdf")
convert(word_file, pdf_file)
easygui.msgbox(f"Word 文档已成功转换为 PDF:{pdf_file}", title="转换成功")
else:
easygui.msgbox("取消操作", title="操作取消")
def pdf_to_word():
pdf_file = easygui.fileopenbox(title="请上传要转换为word格式的pdf文件", default="*.pdf")
# 如果上传了文件,开始执行转换操作
if pdf_file:
docx_name = os.path.splitext(os.path.basename(pdf_file))[0] + ".docx"
docx_path = os.path.join(desktop_path, docx_name)
cv = Converter(pdf_file)
cv.convert(docx_path)
cv.close()
easygui.msgbox(f"PDF 文档已成功转换为 Word:{docx_path}", title="转换成功")
# 如果没上传,被视为取消操作
else:
easygui.msgbox("取消操作", title="操作取消")
choices = ["Word 转换 PDF", "PDF 转换 Word"]
choice = easygui.buttonbox("请选择要执行的操作", "文件转换小工具", choices=choices)
if choice == "Word 转换 PDF":
word_to_pdf()
elif choice == "PDF 转换 Word":
pdf_to_word()
else:
easygui.msgbox("未选择任何操作", title="操作取消")
效果
制作成exe程序
- 安装pyinstaller
pip3 install -i https://pypi.douban.com/simple/ pyinstaller
- 进入脚本所在目录,cmd执行
# --noconsole指的是执行程序后不显示cmd的会话,即执行程序后不会弹出cmd的会话弹窗
pyinstaller --noconsole -F <pyname>
只要没明显报错,基本就可以用
- 会在当前目录下生成build和dist目录
- 双击即可使用
FAQ
Traceback (most recent call last): File "转换器.py", line 173, in <module> File "转换器.py", line 148, in word_to_pdf File "docx2pdf\__init__.py", line 106, in convert File "docx2pdf\__init__.py", line 29, in windows File "tqdm\asyncio.py", line 24, in __init__ File "tqdm\std.py", line 1099, in __init__ File "tqdm\std.py", line 1348, in refresh File "tqdm\std.py", line 1496, in display File "tqdm\std.py", line 462, in print_status File "tqdm\std.py", line 455, in fp_write File "tqdm\utils.py", line 139, in __getattr__ AttributeError: 'NoneType' object has no attribute 'write'
此报错是因为tqdm库(显示进度条的)这个库可能不兼容有什么其他问题,解决方法:
添加以下代码:
buffer = io.StringIO() sys.stdout = buffer sys.stderr = buffer