说明:在使用Minio服务器时,无法对word文件预览,如果有需要的话,可以将word文件转为pdf文件,再存储到Minio中,本文介绍如何批量将word文件,转为pdf格式的文件;

安装库
首先,需要安装一个库,pywin32
;

可以在cmd窗口敲下面的命令安装,使用阿里云镜像:
powershell
pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/
如果你使用的是pycharm,我建议直接在软件里安装,如下:

编码
代码如下:
python
import os
import time
import win32com.client
def convert_to_pdf(input_path, output_path):
# 使用win32com对象打开Word应用程序
word = win32com.client.Dispatch("Word.Application")
# 去除程序界面显示
word.Visible = 0
# 打开Word文档
doc = word.Documents.Open(input_path)
# 将Word文档保存为PDF文件
doc.SaveAs(output_path, FileFormat=17)
# 关闭Word文档
doc.Close()
# 关闭Word应用程序
word.Quit()
def main(input_path, output_path, file):
try:
# 转换为绝对路径
input_path = os.path.abspath(input_path + "\\" + file)
if file[-4:] == "docx":
output_path = os.path.abspath(output_path + "\\" + file[:-5] + ".pdf")
else:
output_path = os.path.abspath(output_path + "\\" + file[:-4] + ".pdf")
# 调用函数进行转换
convert_to_pdf(input_path, output_path)
print("转换成功!")
except Exception as e:
print(f"转换失败: {str(e)}")
if __name__ == "__main__":
# 输入路径
input_path = r""
# 输出路径
output_path = r""
# 获取输入路径下的所有文件
listdir = os.listdir(input_path)
# 遍历所有文件
for file in listdir:
# 判断是否为Word文档
if file[-4:] == "docx" or file[-3:] == "doc":
main(input_path, output_path, file)
# 休眠2秒,防止Word应用程序未关闭就进行下一次转换
time.sleep(2)
测试
例如桌面上test文件夹里,有一个word文件;

启动程序,进行转换;

转换完成;
