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)
相关推荐
Olamyh8 小时前
【 超越 ReAct:手搓 Plan-and-Execute (Planner) Agent】
python·ai
deepxuan8 小时前
Day7--python
开发语言·python
曲幽8 小时前
FastAPI不止于API:手把手教你用Jinja2打造动态Web页面
python·fastapi·backend·jinja2·full stack·template engine·web development
禹凕8 小时前
Python编程——进阶知识(多线程)
开发语言·爬虫·python
Ulyanov8 小时前
基于Pymunk物理引擎的2D坦克对战游戏开发
python·游戏·pygame·pymunk
铉铉这波能秀8 小时前
LeetCode Hot100数据结构背景知识之字典(Dictionary)Python2026新版
数据结构·python·算法·leetcode·字典·dictionary
骆驼爱记录8 小时前
Word样式检查器使用指南
自动化·word·excel·wps·新人首发
程序媛徐师姐9 小时前
Python基于爬虫的网络小说数据分析系统【附源码、文档说明】
爬虫·python·python爬虫·网络小说数据分析系统·pytho网络小说数据分析系统·python爬虫网络小说·python爬虫的网络小说数据
清水白石0089 小时前
深入解析 LRU 缓存:从 `@lru_cache` 到手动实现的完整指南
java·python·spring·缓存
JaydenAI9 小时前
[LangChain之链]LangChain的Chain——由Runnable构建的管道
python·langchain