from win32com.client import gencache
from win32com.client import constants, gencache
def createPdf(wordPath, pdfPath):
"""word轉pdf
:param wordPath: word文件路徑
:param pdfPath: 生成pdf文件路徑
"""
word = gencache.EnsureDispatch('kwps.Application') #
doc = word.Documents.Open(wordPath, ReadOnly=1)
doc.ExportAsFixedFormat(pdfPath,
constants.wdExportFormatPDF,
Item=constants.wdExportDocumentWithMarkup,
CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
word.Quit(constants.wdDoNotSaveChanges)
if __name__ == '__main__':
createPdf(r'D:\test\test001.docx', r'D:\test\test001.pdf')
注意:上述代碼只在windows平台有效。另外:我自己在測試的時候,用的是WPS,電腦里沒有word office系列的,故而word = gencache.EnsureDispatch('kwps.Application')
這個位置處寫的kwps
,寫wps
不管用哦(已采坑);如果電腦中是word office 系列,則這里要注意修改成word = gencache.EnsureDispatch('Word.Application')
。
以上。