pyhton word转pdf 案例代码

2020-05-20 16:17:05 | 编辑

word转pdf最稳定的方法还是调用com组件,下面是pyhton word转pdf的两种方式,但这之前你的安装 win32com 参考:python异常No module named 'win32com'

import os
from win32com import client
import time


from win32com.client import gencache
from win32com.client import constants, gencache


def createPdf():
    """
    word转pdf 推荐这种方式
    :param wordPath: word文件路径
    :param pdfPath:  生成pdf文件路径
    """
    print ('启动')
    print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    
    word = gencache.EnsureDispatch('Word.Application')


    print ('打开')
    print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    
    doc = word.Documents.Open("d:/wordTest/错题与提分练习.docx", ReadOnly=1)
    print ('保存')
    print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    doc.ExportAsFixedFormat("d:/wordTest/ctytflx10000.pdf",
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

    print ('完成')
    print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    
    word.Quit(constants.wdDoNotSaveChanges)


def doc2pdf():

    try:
        print ('启动')
        print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        word = client.DispatchEx("Word.Application")

            

        print ('打开')
        print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))


        worddoc = word.Documents.Open("d:/wordTest/错题与提分练习.docx",ReadOnly = 1)

        print ('保存')
        print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

        worddoc.SaveAs("d:/wordTest/ctytflx1.pdf", FileFormat = 17)

        print ('完成')
        print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
        

        
        worddoc.Close()
        word.Close()
        

    except Exception as e:
         print(e)




doc2pdf()
createPdf()
    

 

登录后即可回复 登录 | 注册
    
关注编程学问公众号