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('--------------文檔已全部轉換完成-----------------------')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM