python办公自动化实例(一):批量转换word文件为PDF

场景:有大批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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值