使用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相关的基础知识。

相关推荐
“AI国潮设计-小江”5 小时前
《Python+SDXL实战:用ControlNet精准控制“英歌舞翻糖吐司”构图,附批量生成脚本》
开发语言·人工智能·python·prompt·aigc
wenwen_chao6 小时前
Python学习与开发资源合集:实用技巧与工具推荐
python
for_ever_love__7 小时前
函数——参数、lambda、*args与作用域
python·函数·大模型开发·编程基础
东莞市云毅网络有限公司7 小时前
企业资料时效性判定:Last-Modified、正文日期与版本字段三路交叉
python·sqlite·自动化运维·geo·数据监测
Query*7 小时前
深入浅出LangGraph【一】_基础篇
python·ai·langchain
XiaoMaqqqq7 小时前
市面上正规的IP驱动产业新场景新工具哪家强
运维·python·网络协议·tcp/ip
ShyanZh8 小时前
【Python3基础】19-Socket 与 TCP、UDP 编程
python·网络协议·tcp/ip·udp
惊讶的猫8 小时前
工具选对之后还不够:商城 Agent 的参数与权限治理
开发语言·python
天赐范式9 小时前
天赐范式第186天:让方差开始自洽——Bulmer效应的闭式验证
python·数字生命·天赐范式·动态运行时·遗传方差·bulmer效应
泡茶喝茶写代码9 小时前
A股量化数据工程:从 REST 接口到策略信号(第 8 篇):成长能力因子:营收与利润增速
java·python·股票数据api·股票数据api接口·股票量化数据api·股票量化数据接口·股票数据api数据