python批量word转txt_python批量实现Word文件转换为PDF文件

4、批量转换

要实现批量准换,将第2步和第3步的功能组合在一起即可,直接上代码。

# -*- coding:utf-8 -*-

# doc2pdf.py: python script to convert doc to pdf with bookmarks!

# Requires Office 2007 SP2

# Requires python for win32 extension

import glob as gb

import sys

reload(sys)

sys.setdefaultencoding('utf8')

'''

参考:http://blog.csdn.net/rumswell/article/details/7434302

'''

import sys, os

from win32com.client import Dispatch, constants, gencache

# from config import REPORT_DOC_PATH,REPORT_PDF_PATH

REPORT_DOC_PATH = 'D:/2/doc/'

REPORT_PDF_PATH = 'D:/2/doc/'

# Word转换为PDF

def word2pdf(filename):

input = filename + '.docx'

output = filename + '.pdf'

pdf_name = output

# 判断文件是否存在

os.chdir(REPORT_DOC_PATH)

if not os.path.isfile(input):

print u'%s not exist' % input

return False

# 文档路径需要为绝对路径,因为Word启动后当前路径不是调用脚本时的当前路径。

if (not os.path.isabs(input)): # 判断是否为绝对路径

# os.chdir(REPORT_DOC_PATH)

input = os.path.abspath(input) # 返回绝对路径

else:

print u'%s not absolute path' % input

return False

if (not os.path.isabs(output)):

os.chdir(REPORT_PDF_PATH)

output = os.path.abspath(output)

else:

print u'%s not absolute path' % output

return False

try:

print input, output

# enable python COM support for Word 2007

# this is generated by: makepy.py -i "Microsoft Word 12.0 Object Library"

gencache.EnsureModule('{00020905-0000-0000-C000-000000000046}', 0, 8, 4)

# 开始转换

w = Dispatch("Word.Application")

try:

doc = w.Documents.Open(input, ReadOnly=1)

doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,

Item=constants.wdExportDocumentWithMarkup,

CreateBookmarks=constants.wdExportCreateHeadingBookmarks)

except:

print ' exception'

finally:

w.Quit(constants.wdDoNotSaveChanges)

if os.path.isfile(pdf_name):

print 'translate success'

return True

else:

print 'translate fail'

return False

except:

print ' exception'

return -1

if __name__ == '__main__':

# img_path = gb.glob(REPORT_DOC_PATH + "*")

# for path in img_path:

# print path

# rc = word2pdf(path)

# rc = word2pdf('1')

# print rc,

# if rc:

# sys.exit(rc)

# sys.exit(0)

import os

for dirpath, dirnames, filenames in os.walk(REPORT_DOC_PATH):

for file in filenames:

fullpath = os.path.join(dirpath, file)

print fullpath, file

rc = word2pdf(file.rstrip('.docx'))

5、参考资料

利用Python将word 2007的文档转为pdf文件

遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持易采站长站。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值