Files
growth_report/utils/pef_utils.py
2025-12-10 22:36:12 +08:00

96 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import comtypes.client
def ppt_to_pdf_single(ppt_path, pdf_path=None):
"""
单个 PPT 转 PDF
:param ppt_path: PPT 文件路径
:param pdf_path: PDF 输出路径 (可选,默认同名)
"""
ppt_path = os.path.abspath(ppt_path) # COM 接口必须使用绝对路径
if pdf_path is None:
pdf_path = os.path.splitext(ppt_path)[0] + ".pdf"
pdf_path = os.path.abspath(pdf_path)
if not os.path.exists(ppt_path):
print(f"文件不存在: {ppt_path}")
return False
powerpoint = None
try:
# 启动 PowerPoint 应用
powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
powerpoint.Visible = 1 # 设为可见,否则某些版本会报错
# 打开演示文稿
deck = powerpoint.Presentations.Open(ppt_path)
# 保存为 PDF (文件格式代码 32 代表 PDF)
deck.SaveAs(pdf_path, 32)
deck.Close()
print(f"转换成功: {pdf_path}")
return True
except Exception as e:
print(f"转换失败: {str(e)}")
return False
finally:
if powerpoint:
powerpoint.Quit()
def batch_convert_folder(folder_path):
"""
【推荐】批量转换文件夹下的所有 PPT (只启动一次 PowerPoint速度快)
"""
folder_path = os.path.abspath(folder_path)
if not os.path.exists(folder_path):
print("文件夹不存在")
return
# 获取所有 ppt/pptx 文件
files = [f for f in os.listdir(folder_path) if f.lower().endswith(('.ppt', '.pptx'))]
if not files:
print("没有找到 PPT 文件")
return
print(f"发现 {len(files)} 个文件,准备开始转换...")
powerpoint = None
try:
# 1. 启动应用 (只启动一次)
powerpoint = comtypes.client.CreateObject("PowerPoint.Application")
# 某些环境下需要设为可见,否则无法运行
# powerpoint.Visible = 1
for filename in files:
ppt_path = os.path.join(folder_path, filename)
pdf_path = os.path.splitext(ppt_path)[0] + ".pdf"
# 如果 PDF 已存在,可以选择跳过
if os.path.exists(pdf_path):
print(f"[跳过] 已存在: {filename}")
continue
print(f"正在转换: {filename} ...")
try:
# 打开 -> 另存为 -> 关闭
deck = powerpoint.Presentations.Open(ppt_path)
deck.SaveAs(pdf_path, 32)
deck.Close()
except Exception as e:
print(f"文件 {filename} 转换出错: {e}")
except Exception as e:
print(f"PowerPoint 进程出错: {e}")
finally:
# 2. 退出应用
if powerpoint:
powerpoint.Quit()
print("PowerPoint 已关闭,批量转换完成。")