python批量转化word为PDF

from win32com import client
import os

def doc2pdf(fn):
    word = client.Dispatch("Word.Application")  # open word
    doc = word.Documents.Open(fn)  # open word file
    doc.SaveAs("{}.pdf".format(fn[:-4]), 17)  # 17 means pdf file, save as pdf
    doc.Close()  # close word
    word.Quit()


def docx2pdf(fn):
    word = client.Dispatch("Word.Application")  # open word
    doc = word.Documents.Open(fn)  # open word file
    doc.SaveAs("{}.pdf".format(fn[:-5]), 17)  # save as pdf 17means pdf file    
    doc.Close()  # close word file
    word.Quit()

path=r'C:\Users\Administrator\Desktop\xxx' # file path
files=[]
for file in os.listdir(path):
    if file.endswith(".docx"): #only get word documents
        files.append(path +"\\"+ file)

for d in files:
    docx2pdf(d) #for docx documents
    doc2pdf(d)#for doc documents
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
批量转化Word文件为PDF文件,可以使用Python中的`win32com`模块来自动化Word应用程序,将Word文件转换为PDF格式。具体步骤如下: 1. 安装`win32com`模块。在命令行中输入以下命令: ``` pip install pywin32 ``` 2. 编写Python脚本。以下是一个示例脚本,将指定目录下的所有Word文件转换为PDF文件: ```python import os import win32com.client # Word转换为PDF的函数 def word2pdf(input_file, output_file): word = win32com.client.Dispatch('Word.Application') doc = word.Documents.Open(input_file) doc.SaveAs(output_file, FileFormat=17) doc.Close() word.Quit() # 获取指定目录下的所有Word文件 input_dir = 'C:/input_dir' # 替换为你的输入目录 output_dir = 'C:/output_dir' # 替换为你的输出目录 files = os.listdir(input_dir) word_files = [f for f in files if f.endswith('.doc') or f.endswith('.docx')] # 逐个转换Word文件为PDF文件 for word_file in word_files: input_file = os.path.join(input_dir, word_file) output_file = os.path.join(output_dir, os.path.splitext(word_file)[0] + '.pdf') word2pdf(input_file, output_file) ``` 3. 将脚本打包成可执行文件。可以使用`pyinstaller`模块将Python脚本打包成可执行文件。在命令行中输入以下命令: ``` pip install pyinstaller pyinstaller --onefile your_script_name.py ``` 这将生成一个单独的可执行文件`your_script_name.exe`,可以在不安装Python环境的情况下运行脚本。 注意:由于使用了`win32com`模块,因此该脚本只能在Windows操作系统上运行。如果在其他操作系统上运行脚本,需要使用其他方式将Word文件转换为PDF文件。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yung-hsin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值