說明:在使用Minio服務器時,無法對word文件預覽,如果有需要的話,可以將word文件轉為pdf文件,再存儲到Minio中,本文介紹如何批量將word文件,轉為pdf格式的文件;
安裝庫
首先,需要安裝一個庫,pywin32
;
可以在cmd窗口敲下面的命令安裝,使用阿里云鏡像:
pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/
如果你使用的是pycharm,我建議直接在軟件里安裝,如下:
編碼
代碼如下:
import os
import timeimport win32com.clientdef 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文件;
啟動程序,進行轉換;
轉換完成;