python将文档转换成pdf_使用Python将Microsoft Word文档转换为PDF

1586010002-jmsa.png

I have tons of Word and Excel files. I want to convert many Word files in folders by sub folders to PDF, and I try following code.

This code is not active (I mean there aren't Word convert to PDF) although no error.

xbyMg.png

What could be the problem? Is there another solution?

This is my code:

import os

from win32com import client

path = 'D:\programing\test'

word_file_names = []

word = client.DispatchEx("Word.Application")

for dirpath, dirnames, filenames in os.walk(path):

print (dirpath)

for f in filenames:

if f.lower().endswith(".docx") and re.search('Addendum', f):

new_name = f.replace(".docx", r".pdf")

in_file = word_file_names.append(dirpath + "\\" + f)

new_file = word_file_names.append(dirpath + "\\" + new_name)

doc = word.Documents.Open(in_file)

doc.SaveAs(new_file, FileFormat = 17)

doc.Close()

if f.lower().endswith(".doc") and re.search('Addendum', f):

new_name = f.replace(".doc", r".pdf")

in_file = word_file_names.append(dirpath + "\\" + f)

new_file = word_file_names.append(dirpath + "\\" + new_name)

doc = word.Documents.Open(in_file)

doc.SaveAs(new_file, FileFormat = 17)

doc.Close()

word.Quit()

解决方案

i solved this problem and fixed the code has following

import os

import win32com.client

import re

path = (r'D:\programing\test')

word_file_names = []

word = win32com.client.Dispatch('Word.Application')

for dirpath, dirnames, filenames in os.walk(path):

for f in filenames:

if f.lower().endswith(".docx") :

new_name = f.replace(".docx", ".pdf")

in_file =(dirpath + '/'+ f)

new_file =(dirpath + '/' + new_name)

doc = word.Documents.Open(in_file)

doc.SaveAs(new_file, FileFormat = 17)

doc.Close()

if f.lower().endswith(".doc"):

new_name = f.replace(".doc", ".pdf")

in_file =(dirpath +'/' + f)

new_file =(dirpath +'/' + new_name)

doc = word.Documents.Open(in_file)

doc.SaveAs(new_file, FileFormat = 17)

doc.Close()

word.Quit()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值