Python自动化 word转化pdf
导入模块
#pywin32是WIndows的API from win32com.client import constants,gencache #系统 import os
pywin32是Windows的API,可以直接调用平台程序,os模块包含普遍的操作系统功能。
封装方法
#定义pdf方法 ''' wordPath:word的文件路径 pdfPath:pdf生成的路径 ''' def createpdf(wordPath,pdfPath): #创建word程序对象 word = gencache.EnsureDispatch('Word.Application') #读取word文档的地址 doc = word.Documents.Open(wordPath,ReadOnly=1) #读取路径 读取方式 #转化方法 #此方法可以转变为xps或pdf,第一参数生成转化路径,第二个参数是转化的类型 doc.ExportAsFixedFormat(pdfPath,constants.wdExportFormatPDF) #退出 word.Quit()
定义函数重复运用,创建word对象,再读取指定路径下的word文档,使用文档对象的ExportAsFixedFormat()方法doc转化为pdf,使用word,Quit()退出程序
单文件和多文件转换
wordPath = 'D:/desktop/zdh/info.docx' pdfPath = 'D:/desktop/zdh/info.pdf' #单个文件的转换 createpdf(wordPath,pdfPath) #多个文件的转换 print(os.listdir('.')) #当前文件下的所有文件 #存储word文件名 wordfile = [] for file in os.listdir('.'): #endswith结尾存在 if file.endswith(('.doc','.docx')): #添加到变量数组 wordfile.append(file) print(wordfile) #遍历添加转换 for file in wordfile: #获取文件的绝对变量 filepath = os.path.abspath(file) #获取点的位置 index = filepath.rindex('.') #将后缀拼接改变 pdfpath = filepath[:index]+'.pdf' print(pdfpath) createpdf(filepath,pdfpath)
单文件转换直接调用函数,填入实际参数即可;而多个文件使用os模块获取文件名,然后替换拼接,之后遍历转换即可
    M54

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号