使用win32com将ppt(x)文件转换为pdf文件-代码实例

时间:2024-11-15 10:25:30

需要一些python基础和flask基础

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)

程序结果

在这里插入图片描述

文件内容

在这里插入图片描述