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)
相关推荐
花酒锄作田4 小时前
Postgres - Listen/Notify构建轻量级发布订阅系统
python·postgresql
Thomas.Sir4 小时前
第二章:LlamaIndex 的基本概念
人工智能·python·ai·llama·llamaindex
m0_694845575 小时前
Dify部署教程:从AI原型到生产系统的一站式方案
服务器·人工智能·python·数据分析·开源
李昊哲小课6 小时前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
不知名的老吴6 小时前
返回None还是空集合?防御式编程的关键细节
开发语言·python
李昊哲小课7 小时前
Python办公自动化教程 - 第5章 图表创建 - 让数据可视化
python·信息可视化·数据分析·数据可视化·openpyxl
chushiyunen7 小时前
python pygame实现贪食蛇
开发语言·python·pygame
Dream of maid7 小时前
Python-基础2(流程控制)
python
Lenyiin8 小时前
《Python 修炼全景指南:一》从环境搭建到第一个程序
开发语言·python
涛声依旧393168 小时前
Python项目实战:学生信息管理系统
开发语言·python·数据挖掘