使用win32com将ppt(x)文件转换为pdf文件

本文来记录下如何使用win32com将ppt(x)文件转换为pdf文件

文章目录


win32com概述

Pywin32 是一个用于与 Microsoft Windows 操作系统交互的 Python 扩展模块,它提供了对多个 Windows API 的访问,包括对 Microsoft Office 应用程序(如 Word、Excel、PowerPoint 等)的自动化操作。


win32com优缺点

win32com优点

  • 功能强大:Pywin32 允许您在 Python 中与 Word 进行深度集成,可以实现对 Word 文档的创建、编辑、格式化、内容提取等一系列操作。
  • 自动化处理:通过 Pywin32,您可以编写脚本来自动化执行 Word 相关的任务,如批量处理文档、生成报告、数据导入等,提高工作效率。
  • 广泛的支持:Pywin32 提供了对 Word 的广泛支持,允许您访问和操作 Word 的各种对象、属性和方法,以满足特定的需求。
  • 良好的文档和社区支持:Pywin32 拥有详细的官方文档和活跃的社区支持,您可以轻松地找到示例代码、教程和解决方案,加快开发速度。

win32com缺点

  • Windows 平台限定:Pywin32 是一个针对 Windows 平台的扩展模块,因此在其他操作系统上(如 macOS、Linux)无法使用,这限制了其跨平台的能力。
  • 依赖性:使用 Pywin32 需要安装相应的依赖库和软件,如 Microsoft Office 套件、Windows API 等,这可能增加了部署和配置的复杂性。
  • 学习曲线:Pywin32 的使用需要一定的学习和熟悉过程,特别是对于那些不熟悉 Windows API 和 COM 编程的开发者来说,上手可能会有一定的难度。

代码实例

需要一些python基础和flask基础

python 复制代码
import os
import glob
from win32com.client import gencache
from flask import Flask, send_from_directory, jsonify
from logging.handlers import RotatingFileHandler
from datetime import time
import pythoncom
import logging
import socket



app = Flask(__name__)



# 初始化日志信息
def initLog():

    LOG_FORMAT = "%(asctime)s - %(levelname)s %(name)s %(filename)s [line:%(lineno)d] - %(message)s"
    tfh = logging.handlers.TimedRotatingFileHandler('pdf_log.log', when='S', interval=1.5, backupCount=2,
                                                    encoding='UTF-8', delay=False, utc=False, atTime=time)
    rfh = logging.handlers.RotatingFileHandler(filename='log.log', encoding='UTF-8', maxBytes=1024, backupCount=2)

    sh = logging.StreamHandler()
    logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG, handlers=[rfh, tfh, sh])


def pptToPDF():

    fileName = "ppt模板.pptx"

    print("=======pptToPDF(fileName)=========" + fileName)

    # 线程初始化
    # 解决多线程使用pywin32com造成的问题
    pythoncom.CoInitialize()

    # 需要转换的ppt位置
    filename = "D:\\pdf\\" + fileName
    logging.info("=====需要转换的ppt文件为=======" + filename)

    # ppt转为pdf以后存放的路径
    directory = "D:\pdf"
    logging.info("=====ppt转为pdf以后存放的路径为:=====" + directory)

    # 生成PDF文件的存储路径
    if not os.path.exists(directory):
        # create the directory if it not exits
        os.mkdir(os.path.join(directory))


    pdfName=os.path.basename(filename).split('.ppt')[0]+'.pdf'
    # savePathFile为出参
    savePathFile=os.path.join(directory,pdfName)
    logging.info("======最终保存的ppt路径为=========" + savePathFile)
    # judge if the str savePathFile is a file existed
    if os.path.isfile(savePathFile):
        print(pdfName,"已经转换完成")
        return  savePathFile
    # guessing that has some connections with open the PowerPoint Application
    p=gencache.EnsureDispatch("PowerPoint.Application")
    try:
        # open the PowerPoint file
        ppt=p.Presentations.Open(filename,False,False,False)
    except Exception as e:
        # throw
        print(os.path.split(filename)[1],"File format conversion failed,because %s" %e)
    ppt.ExportAsFixedFormat(savePathFile,2,PrintRange=None)
    print("converted && saved :", savePathFile)
    p.Quit     #close the PowerPoint file

    logging.info("======p.Quit==========="+savePathFile)
    return savePathFile

    # 释放资源
    # pythoncom.CoUninitialize()

def main():

    savePathFile = pptToPDF()
    print(savePathFile)



# 实现ppt文件向pdf文件的转换
if __name__ =="__main__":


    main()
    # print("程序已经执行完成!")
    # inp = input("请按回车键退出程序。")
    initLog()
    # 获取本机的ip地址
    res = socket.gethostbyname(socket.gethostname())
    app.run(host=res,debug=False, port=5002)

程序结果

文件内容


本文小结

本文记录了使用win32com将ppt(x)文件转换为pdf文件,需要有一些python和flask相关的基础知识。

相关推荐
SeaTunnel38 分钟前
从 Python Script 地狱到标准化数据集成框架
大数据·开发语言·python·程序员·代码·seatunnel
深度研习笔记1 小时前
OpenCV工业视觉实战09|项目EXE打包+工控机无环境部署+后台常驻运行,彻底脱离Python环境,完成项目最终交付
python·opencv·webpack
CCPC不拿奖不改名1 小时前
大模型推理架构与开源生态知识整理
数据库·windows·python·架构·langchain·开源·github
Marst Code2 小时前
(python)2026Plotly 库评估:交互式可视化到底值不值得引入?
开发语言·python
databook2 小时前
当散点图不够用时:用 t-SNE 可视化多维数据
python·数据分析·数据可视化
我的xiaodoujiao4 小时前
快速学习Python基础知识详细图文教程9--函数进阶
开发语言·python·学习·测试工具
weixin_408099674 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能
去码头整点薯条ing5 小时前
某当网登录滑块【协议+OCR】
爬虫·python·ocr
赶紧写完去睡觉6 小时前
Anaconda 创建虚拟环境与使用
python·pycharm·conda
迷途呀6 小时前
Python:函数中的参数类型
开发语言·笔记·python·langchain·nlp