word转pdf

https://zhuanlan.zhihu.com/p/140363567
https://downloadarchive.documentfoundation.org/libreoffice/old/6.2.5.2/rpm/x86_64/
https://www.cnblogs.com/ruozhu/p/11190195.html
https://blog.csdn.net/OnlyLove_longshao/article/details/108103178
win
https://www.bbsmax.com/A/LPdooZv8d3/
https://blog.csdn.net/weixin_30920513/article/details/98838846
soffice --headless --convert-to pdf C:/Users/liqiang/Desktop/ww/tt.docx --outdir C:/Users/liqiang/Desktop/ww

 

 

import subprocess
import os
import pythoncom
try:
    from comtypes import client
    # pip install comtypes
except ImportError:
    client = None

try:
    from win32com.client import constants, gencache,Dispatch
    # pip install pypiwin32
except ImportError:
    constants = None
    gencache = None

#1.win系统下生成pdf
def doc2pdf(docPath, pdfPath):
    """
        convert a doc/docx document to pdf format
        :param doc: path to document
        """
    docPathTrue = os.path.abspath(docPath)
    if client is None:#判断环境,linux环境这里肯定为None
        return doc2pdf_linux(docPathTrue, pdfPath)
    pythoncom.CoInitialize()
    word = gencache.EnsureDispatch('Word.Application')
    doc = word.Documents.Open(docPathTrue, ReadOnly=1)
    doc.ExportAsFixedFormat(pdfPath,
                            constants.wdExportFormatPDF,
                            Item=constants.wdExportDocumentWithMarkup,
                            CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

    word.Quit(constants.wdDoNotSaveChanges)



#方式二
# import subprocess
# import pythoncom
#
# try:
#     from comtypes import client
#     # pip install comtypes
# except ImportError:
#     client = None
#
# try:
#     from win32com.client import Dispatch
# except:
#     Dispatch = None
# #3.win
# def doc2pdf(doc_path,pdf_path):
#     if client is None:  # 判断环境,linux环境这里肯定为None
#         return doc2pdf_linux(doc_path, pdf_path)
#     pythoncom.CoInitialize()
#     word = Dispatch('Word.Application')
#     doc = word.Documents.Open(doc_path)
#     # doc.SaveAs(input_file.replace(".docx", ".pdf"), FileFormat=17)
#     doc.SaveAs(pdf_path, FileFormat=17)
#     doc.Close()
#     word.Quit()

# print(doc2pdf(r"E:\Project\806\flyapi\doc\temp\temp.docx",r"E:\Project\806\flyapi\doc\pdf\33.pdf"))

#2.linux下生成pdf
def doc2pdf_linux(docPath, pdfPath):
    cmd = 'libreoffice6.2 --headless --convert-to pdf'.split() + [docPath] + ['--outdir'] + [pdfPath]
    p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
    p.wait(timeout=30)
    stdout, stderr = p.communicate()
    if stderr:
        raise subprocess.SubprocessError(stderr)

 

posted @ 2021-05-20 17:53  心慌得初夏  阅读(141)  评论(0编辑  收藏  举报
levels of contents