簡短的Python代碼,可實現批量地將微軟Powerpoint文件(.ppt或者.pptx)轉換爲pdf格式,具有一定的參考意義。
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 11 16:23:02 2018
@author: hp
"""
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 + ".pdf"
deck = powerpoint.Presentations.Open(inputFileName)
deck.SaveAs(outputFileName,formatType) # formatType = 32 for ppt to pdf
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()
說明:
使用說明:
- PC已下載微軟Powerpoint
- 將Python腳本與PPT文件位於同一個文件夾下。
代碼說明:
1、os.listdir()與os.path.join()的使用
詳見 Python 3.6 :os.listdir()與os.path.join()方法的使用
2、os.getcwd()使用:
作用:
os.getcwd() 方法用於返回當前工作目錄。
語法:
os.getcwd()方法的語法如下:
os.getcwd()
參數:
無
實例:
import os , sys
os.chdir("D:/project/re code/blog")
print("Current working directory:", os.getcwd())
Current working directory: D:\project\re code\blog
代碼參考: