[Asm] 纯文本查看 复制代码 def convert_with_com(self, file_path, output_path):
try:
abs_file_path = str(file_path.absolute())
abs_output_path = str(output_path.absolute())
if file_path.suffix.lower() in ['.doc', '.docx']:
word = win32com.client.Dispatch("Word.Application")
word.Visible = False
word.DisplayAlerts = False # 禁用警告
try:
doc = word.Documents.Open(abs_file_path)
# 修复参数配置
doc.ExportAsFixedFormat(
OutputFileName=abs_output_path,
ExportFormat=17, # wdExportFormatPDF
OpenAfterExport=False,
OptimizeFor=0, # wdExportOptimizeForPrint
BitmapMissingFonts=True,
CreateBookmarks=1 # wdExportCreateHeadingBookmarks
)
doc.Close(SaveChanges=False)
finally:
word.Quit()
elif file_path.suffix.lower() in ['.xls', '.xlsx']:
excel = win32com.client.Dispatch("Excel.Application")
excel.Visible = False
excel.DisplayAlerts = False
try:
wb = excel.Workbooks.Open(abs_file_path)
wb.ExportAsFixedFormat(
Type=0, # xlTypePDF
Filename=abs_output_path,
Quality=0, # xlQualityStandard
IncludeDocProperties=True,
IgnorePrintAreas=False
)
wb.Close(SaveChanges=False)
finally:
excel.Quit()
# 验证文件是否成功创建
if output_path.exists() and output_path.stat().st_size > 0:
return abs_output_path
return None
except Exception as e:
print(f"COM转换失败: {e}")
return None