用python把docx批量转为pdf

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

安装所需库

pip install comtypes

示例代码

# 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)

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下代码将docx文件批量转换为pdf文件: ```python import os from docx2pdf import convert def docx2pdf(input_path): docx_files = \[file for file in os.listdir(input_path) if file.endswith('.docx')\] for docx_file in docx_files: print("开始转换 -> " + docx_file) convert(input_path + '\\' + docx_file) if __name__ == '__main__': docx2pdf('C:/Users/1223/Desktop/OK') ``` 这段代码使用了`docx2pdf`库来实现批量转换。首先,通过`os.listdir`函数获取指定目录下的所有文件,然后筛选出以`.docx`结尾的文件。接下来,使用`convert`函数将每个docx文件转换为pdf文件。最后,调用`docx2pdf`函数并传入目标文件夹的路径即可实现批量转换。 #### 引用[.reference_title] - *1* *3* [如何用Python批量Pdf文档转换成Word文档?](https://blog.csdn.net/weixin_55609727/article/details/127606700)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python 批量将 Word 转换为 PDF](https://blog.csdn.net/weixin_67276852/article/details/130413085)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值