驗證過ppt也可以合並成pdf文件,確實很高效,什么pdf轉換器的再也不用了~
需要下載模塊pywin32,程序中導入模塊為win32com。
# -*- coding:utf-8 -*- import os from win32com.client import Dispatch,DispatchEx from win32com.client import constants from win32com.client import gencache import re def getfilenames(filepath='',filelist_out=[],file_ext='all'): for fpath, dirs, fs in os.walk(filepath): for f in fs: fi_d = os.path.join(fpath, f) if file_ext == '.doc': if os.path.splitext(fi_d)[1] in ['.doc','.docx']: filelist_out.append(re.sub(r'\\','/',fi_d)) else: if file_ext == 'all': filelist_out.append(fi_d) elif os.path.splitext(fi_d)[1] == file_ext: filelist_out.append(fi_d) else: pass filelist_out.sort() return filelist_out # Word to PDF def wordtopdf(filelist,targetpath): valueList = [] try: gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4) # 開始轉換 w = Dispatch("Word.Application") for fullfilename in filelist: (filepath,filename) = os.path.split(fullfilename) # 分割文件路徑和文件名 softfilename = os.path.splitext(filename) # 分割文件名和擴展名 os.chdir(filepath) doc = os.path.abspath(filename) os.chdir(targetpath) pdfname = softfilename[0] + ".pdf" output = os.path.abspath(pdfname) pdf_name = output try: doc = w.Documents.Open(doc, ReadOnly=1) doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF, Item=constants.wdExportDocumentWithMarkup, CreateBookmarks=constants.wdExportCreateHeadingBookmarks) except Exception as e: print(e) if os.path.isfile(pdf_name): valueList.append(pdf_name) else: print('轉換失敗!') return False w.Quit(constants.wdDoNotSaveChanges) return valueList except TypeError as e: print('出錯了!') print(e) return False if __name__ == '__main__': sourcepath = r"E:/xxx/xxx" # 指定源路徑(Word文檔所在路徑) targetpath = r"E:/xxx/xxx/pdf/" # 指定目標路徑(PDF保存路徑) filelist = getfilenames(sourcepath,[],'.doc') # 獲取Word文檔路徑 valueList = wordtopdf(filelist,targetpath) # 實現將Word文檔批量轉換為PDF if valueList: print("轉換成功") else: print("沒有要轉換的Word文檔或者轉換失敗!請檢查!")