用python把docx批量转为pdf

为保证转换质量,本文的方法是通过脚本和com技术调用office自带的程序进行转换的,因此需要电脑已经装有office。如果希望不装office也能用,则需要研究OpenXML技术,后面实在闲的慌(退休)再搞。

安装所需库

bash 复制代码
pip install comtypes

示例代码

python 复制代码
# Copy from Yue Zhang

import os
import comtypes.client

def convert_word_to_pdf(folder_path):
    word = comtypes.client.CreateObject("Word.Application")
    word.Visible = False

    for file in os.listdir(folder_path):
        if file.endswith(".docx") or file.endswith(".doc"):
            in_file = os.path.abspath(os.path.join(folder_path, file))
            out_file = os.path.abspath(os.path.join(folder_path, file.replace(".docx", ".pdf").replace(".doc", ".pdf")))

            doc = word.Documents.Open(in_file)
            doc.SaveAs(out_file, FileFormat=17) # 17 代表 PDF 格式
            doc.Close()

    word.Quit()

# 使用示例
folder_path = '存放docx或者doc文件的文件夹路径'
convert_word_to_pdf(folder_path)
相关推荐
hxxjxw1 天前
Pytorch分布式训练/多卡训练(六) —— Expert Parallelism (MoE的特殊策略)
人工智能·pytorch·python
用户8356290780511 天前
使用 C# 高效解析 PDF 文档:文本与表格提取实战指南
后端·c#
dagouaofei1 天前
PPT AI生成实测报告:哪些工具值得长期使用?
人工智能·python·powerpoint
BoBoZz191 天前
ExtractPolyLinesFromPolyData切割一个三维模型(球体),并可视化切割后产生的多条等高线
python·vtk·图形渲染·图形处理
quikai19811 天前
python练习第六组
java·前端·python
rit84324991 天前
C#实现的远程控制系统
前端·javascript·c#
Trouville011 天前
Python中encode和decode的用法详解
开发语言·python
belldeep1 天前
python:backtrader 使用指南
python·backtrader·量化回测
codingPower1 天前
制作ftl文件通过FreeMarke生成PDF文件(含图片处理)
java·开发语言·pdf