form1.cn
Make a little progress every day

Python批量将PPT文件转为PDF文件

15th of September 2022 Python Code 242

Python批量将PPT文件转为PDF文件

# -*- coding: utf-8 -*-

'''
Python批量将PPT文件转为PDF文件
'''

# 导入包
import comtypes.client
# 需要安装模块 pip install comtypes
import os


# 定义方法
def init_powerpoint():
    '''初始化PPT'''
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1
    return powerpoint


def ppt_to_img(powerpoint, inputFileName, outputFileName, imgpath):
    '''PPT转图片操作'''
    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName[0:-4] + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    # 设置输出名称
    namear = os.path.split(outputFileName)
    minimgpath = namear[1].replace(".pdf",".pdf")
    minimgpath = minimgpath.replace("..",".")
    minimgpath = os.path.join(imgpath, minimgpath)
    # 17数字是ppt转图片,32数字是ppt转pdf。
    deck.SaveAs(minimgpath, 32)
    deck.Close()


def convert_files_in_folder(powerpoint, folder, imgpath):
    '''过滤所有PPT文件并加入转换'''
    if not os.path.exists(imgpath):
        os.makedirs(imgpath)
    files = os.listdir(folder)
    pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    for pptfile in pptfiles:
        fullpath = os.path.join(folder, pptfile)
        print('转换成功:' + fullpath)
        ppt_to_img(powerpoint, fullpath, fullpath, imgpath)


if __name__ == "__main__":


    # PPT文件的存放目录
    pptpath = r'D:\Test\pptx'

    # 保存转换后PDF的目录
    imgpath = r'D:\Test\pdf'

    # 遍历所有PPT文件并转换
    powerpoint = init_powerpoint()
    convert_files_in_folder(powerpoint, pptpath, imgpath)
    powerpoint.Quit()