场景:有大批word文件需要转PDF,手动word转pdf速度很慢,尤其当word文件很大的时候,这时候就可以使用程序高效批量转换word文件了。
实现效果如下图所示
代码如下:
#!user/bin/python3
# _*_ coding:utf-8 _*_
# author TingXiao-UI
import os
from win32com import client
from shutil import copyfile
#遍历word文件、转换为pdf
def ergodicPdf(rp):
print('开始转换!')
# 创建合并文件夹
printFlodPath = os.getcwd() + '\\打印'
a = os.path.exists(printFlodPath)
if a!=True:
os.mkdir(printFlodPath)
#遍历Word文件
for root,dirs,files in os.walk(rp):
for file in files:
curPdf = os.path.join(file)
curPdfPath = os.path.join(root,file)
#指定word格式,过滤不符合要求的文件
if curPdfPath.find('.docx')>=0 and file.find('~$')<0 :
index1 = curPdfPath.rfind('d')
index2 = file.rfind('d')
pdfPath = curPdfPath[:index1]+'pdf'
pdfName = file[:index2]+'pdf'
print(pdfName)
wordToPdf(curPdfPath,pdfName,pdfPath,printFlodPath)
#word转pdf
def wordToPdf(wp,pn,pp,printPath):
if not os.path.exists(pp):
word = client.DispatchEx("Word.Application")
worddoc = word.Documents.Open(wp,ReadOnly = 1)
worddoc.SaveAs(printPath+'\\'+pn, FileFormat = 17)
worddoc.Close()
word.Quit()
if __name__=='__main__':
rootPath = os.getcwd()#获取当前文件路径
# rootPath = input('请输入文件路径(结尾加上/):')
ergodicPdf(rootPath)#合并PDF