PPT转化成PDF脚本

发布于:2025-09-12 ⋅ 阅读:(17) ⋅ 点赞:(0)

功能:把当前目录下面的所有ppt转化成PDF

有环境的可以自己运行或者修改脚本,没有的文章底部有打包好的链接

import os
import win32com.client
import pythoncom
import shutil

def 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 = None
    presentation = None
    
    # 检查文件是否可访问
    if not os.path.exists(pptx_path):
        print(f"错误: 文件不存在 - {pptx_path}")
        return False
        
    if not os.access(pptx_path, os.R_OK):
        print(f"错误: 没有读取权限 - {pptx_path}")
        return False
    
    try:
        # 初始化COM库
        pythoncom.CoInitialize()
        
        # 创建PowerPoint应用对象
        powerpoint = win32com.client.DispatchEx("PowerPoint.Application")  # 使用DispatchEx避免冲突
        powerpoint.Visible = True
        powerpoint.DisplayAlerts = False  # 禁用警告
        
        # 尝试打开文件,增加只读模式
        presentation = powerpoint.Presentations.Open(
            FileName=pptx_path,
            ReadOnly=True,
            WithWindow=False  # 不显示窗口但保持应用可见
        )
        
        # 保存为PDF
        presentation.SaveAs(pdf_path, 32)  # 32 = ppSaveAsPDF
        print(f"已转换: {os.path.basename(pptx_path)} -> {os.path.basename(pdf_path)}")
        return True
        
    except Exception as e:
        print(f"转换失败 {os.path.basename(pptx_path)}:")
        print(f"  错误信息: {str(e)}")
        print(f"  错误类型: {type(e).__name__}")
        return False
        
    finally:
        # 关闭演示文稿
        if presentation is not None:
            try:
                presentation.Close()
            except Exception as close_err:
                print(f"关闭演示文稿时出错: {str(close_err)}")
        
        # 关闭PowerPoint
        if powerpoint is not None:
            try:
                powerpoint.Quit()
            except Exception as quit_err:
                print(f"关闭PowerPoint时出错: {str(quit_err)}")
        
        # 释放资源
        del presentation
        del powerpoint
        pythoncom.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文件")
        return
    
    print(f"找到 {len(pptx_files)} 个PPTX文件,开始转换...")
    success_count = 0
    
    for 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 += 1
    
    print(f"\n转换完成!成功: {success_count}/{len(pptx_files)}")

if __name__ == "__main__":
    # 以管理员权限运行的提示
    print("注意:如果转换失败,尝试以管理员身份运行此脚本\n")
    batch_convert_pptx_to_pdf()
    

打包好的链接:https://wwsj.lanzout.com/i7JtC35uvzxi
密码:3tda


网站公告

今日签到

点亮在社区的每一天
去签到