python办公自动化(1)实现批量word转PDF

 1 from win32com.client import gencache
 2 from win32com.client import constants, gencache
 3 import os,re
 4 def createPdf(wordPath, pdfPath):
 5   """
 6   word转pdf
 7   :param wordPath: word文件路径
 8   :param pdfPath: 生成pdf文件路径
 9   """
10   word = gencache.EnsureDispatch('Word.Application')
11   doc = word.Documents.Open(wordPath, ReadOnly=1)
12   doc.ExportAsFixedFormat(pdfPath,
13               constants.wdExportFormatPDF,
14               Item=constants.wdExportDocumentWithMarkup,
15               CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
16   word.Quit(constants.wdDoNotSaveChanges)
17 ###批量转换
18 for dirs,subdirs,files in os.walk(os.getcwd()):
19     for name in files:
20         if re.search('\.(doc|docx)', name):
21             #print(dirs,subdirs,name)
22             if subdirs:
23               createPdf(dirs+subdirs+name,re.subn('(doc|docx)', 'pdf', name))
24             else:
25                createPdf(dirs+'\\'+name,dirs+'\\'+re.subn('(doc|docx)', 'pdf', name)[0])
26 
27 
28         print('--------------文档已全部转换完成-----------------------')

 

posted @ 2020-05-14 15:21  sky_on_the_way  阅读(1476)  评论(2)    收藏  举报