使用Python将Microsoft Word文档转换为PDF [英] Convert Microsoft Word document to PDF using Python

查看:2416
本文介绍了使用Python将Microsoft Word文档转换为PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大量的Word和Excel文件.我想将子文件夹中的文件夹中的许多Word文件转换为PDF,然后尝试执行以下代码.

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.

此代码未激活(我没有将Word转换为PDF),尽管没有错误.

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

可能是什么问题?还有其他解决方案吗?

What could be the problem? Is there another solution?

这是我的代码:

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

这篇关于使用Python将Microsoft Word文档转换为PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆