环境安装: pip install win32com 或者下载安装包安装 pip install pywin32-223-cp36-cp36m-win_amd64.whl
demo1:
# -*- encoding: utf-8 -*-
import os
from win32com import client
#pip instatll win32com
def doc2pdf(doc_name, pdf_name):
"""
:word文件转pdf
:param doc_name word文件名称
:param pdf_name 转换后pdf文件名称
"""
try:
word = client.DispatchEx("Word.Application")
if os.path.exists(pdf_name):
os.remove(pdf_name)
worddoc = word.Documents.Open(doc_name,ReadOnly = 1)
worddoc.SaveAs(pdf_name, FileFormat = 17)
worddoc.Close()
return pdf_name
except:
return 1
if __name__=='__main__':
doc_name = "D:/test1.docx"
ftp_name = "D:/test1.pdf"
doc2pdf(doc_name, ftp_name)
demo2(推荐使用):
from win32com import client
def wordToPdf(docname,pdfname):
w = client.Dispatch("Word.Application")
doc = w.Documents.Open(docname)
doc.ExportAsFixedFormat(pdfname, client.constants.wdExportFormatPDF)
#w.Quit()
def excelToPdf(xlsname,pdfname):
xlApp = client.Dispatch("Excel.Application")
books = xlApp.Workbooks.Open(xlsname)
books.ExportAsFixedFormat(0, pdfname)
#xlApp.Quit()
def pptToPdf(pptname,pdfname):
p = client.Dispatch("PowerPoint.Application")
ppt = p.Presentations.Open(pptname, False, False, False)
ppt.ExportAsFixedFormat(pdfname, 2, PrintRange=None)
#p.Quit()
if __name__=='__main__':
doc_name = "D:/test1.docx"
ftp_name = "D:/test5.pdf"
wordToPdf(doc_name, ftp_name)
xls_name = "D:/test.xls"
ftp_name = "D:/test6.pdf"
excelToPdf(xls_name, ftp_name)
ppt_name = "D:/test.ppt"
ftp_name = "D:/test7.pdf"
pptToPdf(ppt_name, ftp_name)