用python快速批量把word转换为pdf
- 需要用到的模块为pywin32 以及python3
下载传送门win32 点我下载
目录解构详情,word文件放在脚本文件同级即可
完成转换
代码整体
from win32com.client import constants,gencache
import os #目录的操作
def createpdf(wordPath,pdfPath):
word=gencache.EnsureDispatch('Word.Application')
doc=word.Documents.Open(wordPath,ReadOnly=1)
#转换方法
doc.ExportAsFixedFormat(pdfPath,constants.wdExportFormatPDF)
word.Quit()
#多个文件的转换
print(os.listdir('C:\\Users\\Administrator\\Desktop\\testpdf')) #当前文件夹下的所有文件
wordfiles=[]
for file in os.listdir('C:\\Users\\Administrator\\Desktop\\testpdf'):
if file.endswith(('.doc','.docx')): #通过后缀找出所有的workd文件
wordfiles.append(file)
print(wordfiles)
#文件路径和输出路径看你的情况来,发现py获取的当前路径有点问题所以只能绝对路径
for file in wordfiles:
#获取文件路径
filepath='C:\\Users\\Administrator\\Desktop\\testpdf\\'+file #文件的路径
putpath = 'C:\\Users\\Administrator\\Desktop\\testpdf\\hh\\'+file #输出文件的路径
print(filepath)
index=putpath.rindex('.')
#通过截取获取pdfpath
pdfpath=putpath[:index]+'.pdf'
print(pdfpath)
createpdf(filepath,pdfpath)