办公自动化9-批量word转pdf

有些时候工作中需要批量将word转为pdf,那我们就可以用以下的代码啦

import os
import re
from win32com import client
import pandas as pd 

#定义word转pd函数
def doc2pdf(doc_name, pdf_name):
    try:
        word = client.DispatchEx("Word.Application")
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        worddoc = word.Documents.Open(doc_name, ReadOnly=1)
        worddoc.SaveAs(pdf_name, FileFormat=17)
        worddoc.Close()
        return pdf_name
    except:
        return 1

path = r'E:换电脑PYwork办公自动化'#原始存放word的路径
doc_name = [x for x in os.listdir(path) if os.path.isfile(x) and os.path.splitext(x)[1]=='.doc']#列出指定后缀文件夹
replace=re.compile(r'.(doc|docx)',re.I)
for doc in doc_name:
    doc_name_path = os.path.join(path,doc)
    pdf_name_path = os.path.join(path,replace.sub('',doc)+'.pdf')
    doc2pdf(doc_name_path, pdf_name_path)

有问题欢迎留言哦~

原文地址:https://www.cnblogs.com/lizitingxue/p/12531694.html