windows下python批量转换ppt为图片和PDF

版权声明:经验之谈,不知能否换包辣条,另,转载请注明出处。 https://blog.csdn.net/zhezhebie/article/details/81565914

写了个小脚本,批量的将ppt,pptx转换为pdf和jpg

windows下面需要先安装:

comtypes模块

pip3 install  comtypes

代码部分:

import comtypes.client
import os

def init_powerpoint():
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1
    return powerpoint

def ppt_to_pdf(powerpoint, inputFileName, outputFileName, formatType = 32):
    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName[0:-4] + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.SaveAs(inputFileName.rsplit('.')[0] + '.jpg', 17)
    deck.Close()

def convert_files_in_folder(powerpoint, folder):
    files = os.listdir(folder)
    pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    for pptfile in pptfiles:
        fullpath = os.path.join(cwd, pptfile)
        ppt_to_pdf(powerpoint, fullpath, fullpath)

if __name__ == "__main__":
    powerpoint = init_powerpoint()
    cwd = os.getcwd()
    convert_files_in_folder(powerpoint, cwd)
    powerpoint.Quit()

效果如下:

在这里插入图片描述

图片文件夹:

在这里插入图片描述

递归的改变:

# coding=UTF-8
import comtypes.client
import os

def init_powerpoint():
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1
    return powerpoint

def ppt_to_pdf(powerpoint, inputFileName, outputFileName, formatType = 32):
    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName[0:-4] + ".pdf"
    # print(inputFileName,outputFileName)
    # input()
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.SaveAs(inputFileName.rsplit('.')[0] + '.jpg', 17)
    deck.Close()

def convert_files_in_folder(powerpoint, folder):
    files = os.listdir(folder)
    # print(folder,files)
    # input()

    pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    for pptfile in pptfiles:
        fullpath = os.path.join(folder, pptfile)
        # print(fullpath,pptfile)
        # input() 
        ppt_to_pdf(powerpoint, fullpath, fullpath)

def getallfiles(path):
    allfile = []
    for dirpath, dirnames, filenames in os.walk(path):
        for dir in dirnames:
            allfile.append(os.path.join(dirpath, dir))
        # for name in filenames: #遍历文件
        # allfile.append(os.path.join(dirpath, name)) #拼接文件夹和文件名
    return allfile

if __name__ == "__main__":
    powerpoint = init_powerpoint()
    cwd = os.getcwd()
    allDirs=getallfiles(cwd)
    for dirname in allDirs:
        convert_files_in_folder(powerpoint, dirname)
    powerpoint.Quit()
阅读更多

更多精彩内容