当前位置: 首页 > news >正文

使用Python批量将Word文件转为PDF文件

说明:在使用Minio服务器时,无法对word文件预览,如果有需要的话,可以将word文件转为pdf文件,再存储到Minio中,本文介绍如何批量将word文件,转为pdf格式的文件;

在这里插入图片描述

安装库

首先,需要安装一个库,pywin32

在这里插入图片描述

可以在cmd窗口敲下面的命令安装,使用阿里云镜像:

pip install pywin32 -i https://mirrors.aliyun.com/pypi/simple/

如果你使用的是pycharm,我建议直接在软件里安装,如下:

在这里插入图片描述

编码

代码如下:

import os
import timeimport win32com.clientdef convert_to_pdf(input_path, output_path):# 使用win32com对象打开Word应用程序word = win32com.client.Dispatch("Word.Application")# 去除程序界面显示word.Visible = 0# 打开Word文档doc = word.Documents.Open(input_path)# 将Word文档保存为PDF文件doc.SaveAs(output_path, FileFormat=17)# 关闭Word文档doc.Close()# 关闭Word应用程序word.Quit()def main(input_path, output_path, file):try:# 转换为绝对路径input_path = os.path.abspath(input_path + "\\" + file)if file[-4:] == "docx":output_path = os.path.abspath(output_path + "\\" + file[:-5] + ".pdf")else:output_path = os.path.abspath(output_path + "\\" + file[:-4] + ".pdf")# 调用函数进行转换convert_to_pdf(input_path, output_path)print("转换成功!")except Exception as e:print(f"转换失败: {str(e)}")if __name__ == "__main__":# 输入路径input_path = r""# 输出路径output_path = r""# 获取输入路径下的所有文件listdir = os.listdir(input_path)# 遍历所有文件for file in listdir:# 判断是否为Word文档if file[-4:] == "docx" or file[-3:] == "doc":main(input_path, output_path, file)# 休眠2秒,防止Word应用程序未关闭就进行下一次转换time.sleep(2)

测试

例如桌面上test文件夹里,有一个word文件;

在这里插入图片描述

启动程序,进行转换;

在这里插入图片描述

转换完成;

在这里插入图片描述

http://www.lryc.cn/news/128103.html

相关文章:

  • XDR解决方案成为了新的安全趋势
  • 001-Nacos 服务注册
  • 71 # 协商缓存的配置:通过内容
  • 【服务器】Strace显示后台进程输出
  • centos如何安装libssl-dev libsdl-dev libavcodec-dev libavutil-dev ffmpeg
  • 2022年12月 C/C++(二级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • 详谈MongoDB的那些事
  • 企业电子招投标采购系统源码之电子招投标的组成 tbms
  • Android 13 添加自定义分区,恢复出厂设置不被清除
  • 改进YOLO系列:1.添加SE注意力机制
  • RP2040开发板自制树莓派逻辑分析仪
  • git clone -b与git pull origin <branch_name>的区别
  • 中期国际:MT4数据挖掘与分析方法:以数据为导向,制定有效的交易策略
  • Linux命令(70)之bzip2
  • ubuntu下gif动态图片的制作
  • 56.linux 进程管理命令和用户管理命令
  • Mac os 上的apt-get install 就是brew install
  • vue watch监听对象 新旧值一样
  • 学习Vue:测试与调试
  • pg使用sql将文本字符串转换成时间格式
  • WordPress中实现层级文章的访问权限继承
  • CSS常见单位汇总
  • LLM - 大模型评估指标之 BLEU
  • http学习笔记3
  • 【Redis】Redis 的主从同步
  • 文本图片怎么转Excel?分享一些好用的方法
  • 大数据-玩转数据-Flink 自定义Sink(Mysql)
  • linux17 线程安全 线程同步
  • lvs集群与nat模式
  • 【开源分享】在线客服系统搭建-基于php和swoole客服系统CRMchat(附源码完整搭建教程)...