使用python将word转为pdf

这种方法,依赖的是window环境,在其他环境中使用会出现问题
from win32com.client import constants, gencache
def createPdf(wordPath, pdfPath):
    """
    word转pdf
    :param wordPath: word文件路径
    :param pdfPath:  生成pdf文件路径
    """
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(wordPath, ReadOnly=1)
    doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
    word.Quit(constants.wdDoNotSaveChanges)
 本以为通过上面的方法将word转pdf,可以实现需求,奈何上传服务之后,使用了linux系统,这种方法就不能够使用。经过多方寻找,只要我们服务器上面的libreoffice安装好,且环境页配置完成,就可以使用如下方法,来实现word转pdf:
import os
os.system("libreoffice6.4 --headless --convert-to pdf --outdir /root/Conv/ /root/TEST.docx")

  以上两种方法,可以分别实现window系统和linux系统中word转pdf。

 
原文地址:https://www.cnblogs.com/lxz123/p/13630770.html