PPT转化成PDF脚本

功能:把当前目录下面的所有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

相关推荐
开开心心_Every11 小时前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
2601_9622994914 小时前
使用 Python 将 CSV 转为 PDF(含表格样式美化)
python·pdf·csv·spire.xls·表格样式
ms365copilot18 小时前
Copilot PowerPoint品牌套件模板设置教程
powerpoint·copilot
tianyue10021 小时前
PDFsam Basic PDF 分割、合并
pdf
SunnyDays10111 天前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
开发语言·python·pdf
SamChan901 天前
PDF翻译服务端到端基准测试:4款主流方案的吞吐量、延迟、内存占用对比
服务器·网络·python·ai·pdf·wpf
Felicia-侧听1 天前
PDF怎么转换成Word?3种方法实现PDF转可编辑Word
pdf·word·pdf转word
乘风归趣1 天前
spire.doc.free将word中占位符替换为pdf文件,以及合并PDF
pdf·word
庖丁AI2 天前
PDF 转 Markdown 工具怎么选?AI 知识库和 RAG 场景要注意什么
人工智能·pdf·文档解析
几层山下2 天前
WPS的word文档转pdf java实现不乱格式生成-已解决
java·pdf·word·wps