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)
相关推荐
清水白石0087 小时前
隔离的艺术:用 `unittest.mock` 驯服外部依赖,让测试真正可控
python
码农小韩7 小时前
AIAgent应用开发——大模型理论基础与应用(五)
人工智能·python·提示词工程·aiagent
百锦再8 小时前
Java中的char、String、StringBuilder与StringBuffer 深度详解
java·开发语言·python·struts·kafka·tomcat·maven
Jonathan Star8 小时前
Ant Design (antd) Form 组件中必填项的星号(*)从标签左侧移到右侧
人工智能·python·tensorflow
努力努力再努力wz8 小时前
【Linux网络系列】:TCP 的秩序与策略:揭秘传输层如何从不可靠的网络中构建绝对可靠的通信信道
java·linux·开发语言·数据结构·c++·python·算法
deep_drink9 小时前
【论文精读(三)】PointMLP:大道至简,无需卷积与注意力的纯MLP点云网络 (ICLR 2022)
人工智能·pytorch·python·深度学习·3d·point cloud
njsgcs9 小时前
langchain+vlm示例
windows·python·langchain
勇气要爆发9 小时前
LangGraph 实战:10分钟打造带“人工审批”的智能体流水线 (Python + LangChain)
开发语言·python·langchain
jz_ddk10 小时前
[实战] 从冲击响应函数计算 FIR 系数
python·fpga开发·信号处理·fir·根升余弦·信号成形
醒醒该学习了!10 小时前
如何将json文件转成csv文件(python代码实操)
服务器·python·json