import os
import win32com.client #pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/
import sys
import datetime
def get_real_path():
"""兼容开发与打包环境的路径获取"""
if getattr(sys, 'frozen', False):
base_dir = os.path.dirname(sys.executable)
else:
base_dir = os.path.dirname(os.path.abspath(__file__))
return base_dir
def gen_output_folder(folder):
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
output_folder = os.path.join(folder, f"pdf_{timestamp}")
os.makedirs(output_folder, exist_ok=True)
return output_folder
def get_word_files_from_current_folder(folder):
word_files = []
for file in os.listdir(folder):
if file.endswith(".doc") or file.endswith(".docx"):
word_files.append(os.path.join(folder, file))
return word_files
def detect_office_or_wps():
try:
word = win32com.client.gencache.EnsureDispatch("Word.Application")
return "office"
except:
try:
wps = win32com.client.gencache.EnsureDispatch("Kwps.Application")
return "wps"
except:
return None
def convert_word_to_pdf_auto(input_path, output_path, engine):
if engine == "office":
app = win32com.client.Dispatch("Word.Application")
elif engine == "wps":
app = win32com.client.Dispatch("Kwps.Application")
else:
print("没有检测到可用的 Office 或 WPS")
return
app.Visible = False
try:
doc = app.Documents.Open(input_path)
doc.SaveAs(output_path, FileFormat=17)
doc.Close()
print(f"转换成功:{input_path}")
except Exception as e:
print(f"转换失败:{input_path},原因:{e}")
try:
app.Quit()
except:
print("当前环境不支持 Quit,跳过退出。")
def batch_convert_here():
engine = detect_office_or_wps()
if not engine:
print("系统里没有安装 Office 或 WPS,没法转换")
return
folder = get_real_path()
word_files = get_word_files_from_current_folder(folder)
if not word_files:
print("当前文件夹没有发现 Word 文件")
return
output_folder = gen_output_folder(folder)
for word_file in word_files:
filename = os.path.splitext(os.path.basename(word_file))[0]
pdf_path = os.path.join(output_folder, f"{filename}.pdf")
convert_word_to_pdf_auto(word_file, pdf_path, engine)
print(f"所有文件转换完成啦!PDF 都在 {output_folder} 文件夹里")
if __name__ == "__main__":
try:
batch_convert_here()
print("按 Enter 键退出...")
input()
except Exception as e:
print(e)
print("程序运行错误,按 Enter 键退出...")
input()