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

相关推荐
nightunderblackcat3 分钟前
新手向:Python网络编程,搭建简易HTTP服务器
网络·python·http
李昊哲小课6 分钟前
pandas销售数据分析
人工智能·python·数据挖掘·数据分析·pandas
C嘎嘎嵌入式开发27 分钟前
python之set详谈
开发语言·python
之歆1 小时前
Python-正则表达式-信息提取-滑动窗口-数据分发-文件加载及分析器-浏览器分析-学习笔记
python·学习·正则表达式
往日情怀酿做酒 V17639296381 小时前
pytorch的介绍以及张量的创建
人工智能·pytorch·python
豌豆花下猫2 小时前
Python 潮流周刊#110:JIT 编译器两年回顾,AI 智能体工具大爆发(摘要)
后端·python·ai
June bug2 小时前
【Python基础】变量、运算与内存管理全解析
开发语言·python·职场和发展·测试
蹦蹦跳跳真可爱5893 小时前
Python----OpenCV(几何变换--图像平移、图像旋转、放射变换、图像缩放、透视变换)
开发语言·人工智能·python·opencv·计算机视觉
蹦蹦跳跳真可爱5893 小时前
Python----循环神经网络(Transformer ----Layer-Normalization(层归一化))
人工智能·python·rnn·transformer
m0_625686553 小时前
Day58
python