PYTHON office文档转换为pdf格式

发布时间 2023-03-22 21:17:04作者: 叁只小羊

一、安装 pywin32

pip install pywin32 -i https://pypi.mirrors.ustc.edu.cn/simple

二、excel 转换为PDF文档

import os
from win32com.client import DispatchEx

def excel_to_pdf(from_xls, to_pdf):
    app = DispatchEx("Excel.Application")
    app.Visible = False
    app.DisplayAlerts = 0
    books = app.Workbooks.Open(os.path.abspath(from_xls))
    books.ExportAsFixedFormat(0, os.path.abspath(to_pdf))
    books.Close(False)
    app.Quit()

可以通过位置或名称选定某个工作表进行转换。

def excel_sheet_to_pdf(from_xls, to_pdf, index=1, sheet_name=None):
    app = DispatchEx("Excel.Application")
    app.Visible = False
    app.DisplayAlerts = 0
    books = app.Workbooks.Open(os.path.abspath(from_xls), False)

    if sheet_name is not None:
        # 如果指定了工作表名称,则读取这个工作表
        sh = books.Worksheets(sheet_name)
    else:
        # 默认获取第一个索引的工作表
        # index=1 表示第一个工作表,index=2表示第二个工作表
        name = books.Sheets(index).Name
        sh = books.Worksheets(name)

    sh.ExportAsFixedFormat(0, os.path.abspath(to_pdf))
    books.Close(False)
    app.Quit()

三、word 转换为PDF文档

def word_to_pdf(from_doc, to_pdf):
      gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
      w = Dispatch("Word.Application")
      doc = w.Documents.Open(os.path.abspath(from_doc))
      doc.ExportAsFixedFormat(os.path.abspath(to_pdf), constants.wdExportFormatPDF,
                              Item=constants.wdExportDocumentWithMarkup,
                              CreateBookmarks=constants.wdExportCreateHeadingBookmarks)
      w.Quit(constants.wdDoNotSaveChanges)

四、ppt 转换为PDF文档

def ppt_to_pdf(from_ppt, to_pdf):
    gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)
    p = Dispatch("PowerPoint.Application")
    ppt = p.Presentations.Open(os.path.abspath(from_ppt), False, False, False)
    ppt.ExportAsFixedFormat(os.path.abspath(to_pdf), 2, PrintRange=None)
    p.Quit()