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)
相关推荐
HAPPY酷1 分钟前
构建即自由:一份为创造者设计的 Windows C++ 自动化构建指南
开发语言·c++·ide·windows·python·策略模式·visual studio
瑶池酒剑仙3 分钟前
Libvio.link爬虫技术解析大纲
爬虫·python
喵手10 分钟前
Python爬虫实战:构建 Steam 游戏数据库:requests+lxml 实战游戏列表采集与价格监控(附JSON导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集steam商店游戏列表数据·sqlite数据库存放采集数据·价格监控游戏推荐市场分析
老蒋每日coding19 分钟前
LangGraph:从入门到Multi-Agent超级智能体系统进阶开发
开发语言·python
岚天start29 分钟前
Python HTTP服务器添加简单用户名密码认证的三种方案
服务器·python·http
cuber膜拜38 分钟前
Weaviate 简介与基本使用
数据库·python·docker·向量数据库·weaviate
开开心心_Every41 分钟前
家常菜谱软件推荐:分类齐全无广告步骤详细
linux·运维·服务器·华为od·edge·pdf·华为云
HealthScience43 分钟前
DNA具体怎么转为蛋白质的?
python
PacosonSWJTU1 小时前
mac-python解释器理解与python安装
开发语言·python
urkay-1 小时前
Android 中实现 HMAC-SHA256
android·开发语言·python