PPT转化成PDF脚本
功能:把当前目录下面的所有ppt转化成PDF
有环境的可以自己运行或者修改脚本,没有的文章底部有打包好的链接
import os
import win32com.client
import pythoncom
import shutildef create_output_dir(output_dir):"""创建输出目录,如果已存在则保留文件(不再清空)"""if not os.path.exists(output_dir):os.makedirs(output_dir)print(f"已创建输出目录: {output_dir}")else:print(f"输出目录已存在: {output_dir}")def pptx_to_pdf(pptx_path, pdf_path):"""将单个PPTX文件转换为PDF,增加更多错误处理"""powerpoint = Nonepresentation = None# 检查文件是否可访问if not os.path.exists(pptx_path):print(f"错误: 文件不存在 - {pptx_path}")return Falseif not os.access(pptx_path, os.R_OK):print(f"错误: 没有读取权限 - {pptx_path}")return Falsetry:# 初始化COM库pythoncom.CoInitialize()# 创建PowerPoint应用对象powerpoint = win32com.client.DispatchEx("PowerPoint.Application") # 使用DispatchEx避免冲突powerpoint.Visible = Truepowerpoint.DisplayAlerts = False # 禁用警告# 尝试打开文件,增加只读模式presentation = powerpoint.Presentations.Open(FileName=pptx_path,ReadOnly=True,WithWindow=False # 不显示窗口但保持应用可见)# 保存为PDFpresentation.SaveAs(pdf_path, 32) # 32 = ppSaveAsPDFprint(f"已转换: {os.path.basename(pptx_path)} -> {os.path.basename(pdf_path)}")return Trueexcept Exception as e:print(f"转换失败 {os.path.basename(pptx_path)}:")print(f" 错误信息: {str(e)}")print(f" 错误类型: {type(e).__name__}")return Falsefinally:# 关闭演示文稿if presentation is not None:try:presentation.Close()except Exception as close_err:print(f"关闭演示文稿时出错: {str(close_err)}")# 关闭PowerPointif powerpoint is not None:try:powerpoint.Quit()except Exception as quit_err:print(f"关闭PowerPoint时出错: {str(quit_err)}")# 释放资源del presentationdel powerpointpythoncom.CoUninitialize() # 清理COM库def batch_convert_pptx_to_pdf(output_dir="./out_pdf"):"""批量转换当前目录下的所有PPTX文件"""create_output_dir(output_dir)current_dir = os.getcwd()pptx_files = [f for f in os.listdir(current_dir) if f.lower().endswith('.pptx')]if not pptx_files:print("未找到任何PPTX文件")returnprint(f"找到 {len(pptx_files)} 个PPTX文件,开始转换...")success_count = 0for pptx_file in pptx_files:pptx_path = os.path.abspath(os.path.join(current_dir, pptx_file))pdf_filename = os.path.splitext(pptx_file)[0] + ".pdf"pdf_path = os.path.abspath(os.path.join(output_dir, pdf_filename))if pptx_to_pdf(pptx_path, pdf_path):success_count += 1print(f"\n转换完成!成功: {success_count}/{len(pptx_files)}")if __name__ == "__main__":# 以管理员权限运行的提示print("注意:如果转换失败,尝试以管理员身份运行此脚本\n")batch_convert_pptx_to_pdf()
打包好的链接:https://wwsj.lanzout.com/i7JtC35uvzxi
密码:3tda