python批量将PPT导出成图片集

导读

需要使用python做一个将很多个不规则PPT导出成用文件夹归纳好的图片集,所以就需要使用comtypes调用本机电脑上的ppt软件,批量打开另存为多张图片

采坑

  • 公司电脑使用comtypes完美导出图片,系统win10
  • 回家后使用自己的电脑就报错,系统也是win10,最后没办法放弃comtypes采用win32com,最终成功

源代码

"""
	该工具函数的功能:批量将PPT导出成图片

"""

import comtypes.client
import os
import win32com
import win32com.client

# base path
BASH_PATH = 'C:\\web\\python\\tool\\formatPPTtaobao\\ppts\\'

# render jpg
RENDER_BASE_PATH = 'C:\\web\\python\\tool\\formatPPTtaobao\\render\\'

# 初始化PPT
def init_powerpoint():
    powerpoint = win32com.client.Dispatch('PowerPoint.Application') #comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1
    return powerpoint

# PPT TO PDF 
def ppt_to_pdf_or_jpg(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()

# save file as a folder
def convert_files_in_folder(powerpoint, folder):
    files = os.listdir(folder)
    pptfiles = [f for f in files if f.endswith((".ppt", ".pptx"))]
    print(pptfiles)
    for pptfile in pptfiles:
        fullpath = os.path.join(cwd, pptfile)
        ppt_to_pdf_or_jpg(powerpoint, fullpath, fullpath)


# delete more ppt and select 20 
def delete_more_ppt(folder):
	files = os.listdir(folder)
	allNum = len(files)
	endPoint = 0
	if(allNum <= 20):
		return
	else:
		endPoint = allNum - 20

	for f in files[0:endPoint]:
		if(os.path.isfile(folder+f)):
			os.unlink(folder+f)

# exec picture composite
def execPictureComposite():
	os.system('python componsite_jpg_taobao.py')
	pass

# delete render jpgs
def deleteRenderJpg():
    jpgs = os.listdir(RENDER_BASE_PATH)
    for jpg in jpgs:
        os.unlink(RENDER_BASE_PATH+jpg)

if __name__ == "__main__":
    cwd = BASH_PATH
    delete_more_ppt(cwd)
    deleteRenderJpg()
    powerpoint = init_powerpoint()
    convert_files_in_folder(powerpoint, cwd)
    powerpoint.Quit()
    execPictureComposite()

你可能感兴趣的:(python)