python实现Word转PDF(comtypes、win32com、docx2pdf)

目录

[使用 comtypes 或 win32com](#使用 comtypes 或 win32com)

使用docx2pdf


使用 comtypes 或 win32com

支持docx和doc格式的文档转PDF,comtypes与win32com底层调用一样,使用方法也一样。保存文件时相当于调用了office中的另存为。只需要修改SaveAs中的FileFormat参数值即可转为对应格式的文件。

|-------------------------------------|--------|
| office 2007支持的全部文件格式对应表 ||
| wdFormatDocument | 0 |
| wdFormatDocument97 | 0 |
| wdFormatDocumentDefault | 16 |
| wdFormatDOSText | 4 |
| wdFormatDOSTextLineBreaks | 5 |
| wdFormatEncodedText | 7 |
| wdFormatFilteredHTML | 10 |
| wdFormatFlatXML | 19 |
| wdFormatFlatXMLMacroEnabled | 20 |
| wdFormatFlatXMLTemplate | 21 |
| wdFormatFlatXMLTemplateMacroEnabled | 22 |
| wdFormatHTML | 8 |
| wdFormatPDF | 17 |
| wdFormatRTF | 6 |
| wdFormatTemplate | 1 |
| wdFormatTemplate97 | 1 |
| wdFormatText | 2 |
| wdFormatTextLineBreaks | 3 |
| wdFormatUnicodeText | 7 |
| wdFormatWebArchive | 9 |
| wdFormatXML | 11 |
| wdFormatXMLDocument | 12 |
| wdFormatXMLDocumentMacroEnabled | 13 |
| wdFormatXMLTemplate | 14 |
| wdFormatXMLTemplateMacroEnabled | 15 |
| wdFormatXPS | 18 |

python 复制代码
# from comtypes import client
from win32com import client


def doc_to_pdf(doc_path, pdf_path):
    # word = client.CreateObject('Word.Application')  # 创建word实例对象
    word = client.Dispatch('Word.Application')
    word.Visible = False  # 不显示Word应用程序窗口
    doc = word.Documents.Open(doc_path)

    doc.SaveAs(pdf_path, FileFormat=17)  # 将文档保存为PDF格式,17代表PDF格式(txt=4, html=10, docx=16, pdf=17)

    # 关闭文档和Word应用程序
    doc.Close()
    word.Quit()

    del doc
    del word

使用docx2pdf

docx2pdf是封装了Windows 系统 win32com 及macos系统处理文件的应用库,只支持docx格式文件转PDF。安装后一行代码即可使用。

安装:pip install docx2pdf

python 复制代码
from docx2pdf import convert

def docx_to_pdf(doc_path, pdf_path):
    convert(doc_path, pdf_path)
相关推荐
smj2302_796826521 分钟前
解决leetcode第3721题最长平衡子数组II
python·算法·leetcode
m0_6265352019 分钟前
力扣题目练习 换水问题
python·算法·leetcode
taxunjishu25 分钟前
DeviceNet 转 MODBUS TCP:倍福 CX 系列 PLC 与 MES 系统在 SMT 回流焊温度曲线监控的通讯配置案例
运维·人工智能·物联网·自动化·区块链
软件技术NINI31 分钟前
MATLAB疑难诊疗:从调试到优化的全攻略
javascript·css·python·html
南风微微吹35 分钟前
26考研英语一、二真题试卷及答案解析PDF电子版(1980-2025年)
考研·pdf
2501_9159214338 分钟前
iOS 应用代上架流程,多工具组合与使用 开心上架 跨平台自动化上传指南
android·ios·小程序·uni-app·自动化·cocoa·iphone
Q_Q19632884751 小时前
python+uniapp基于微信小程序的助眠小程序
spring boot·python·小程序·django·flask·uni-app·node.js
ZYMFZ1 小时前
python面向对象
前端·数据库·python
wangqiaowq1 小时前
ImmutableList.of() 是 Google Guava 库 提供的一个静态工厂方法,用于创建一个不可变的(immutable)列表。
开发语言·windows·python