300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > Python - 批量转换Word文件为PDF文件

Python - 批量转换Word文件为PDF文件

时间:2022-10-27 08:04:39

相关推荐

Python - 批量转换Word文件为PDF文件

1,目的

通过万能的Python把一个目录下的所有Word文件转换为PDF文件。

2,遍历目录

作者总结了三种遍历目录的方法,分别如下。

2.1,调用glob

遍历指定目录下的所有文件和文件夹,不递归遍历,需要手动完成递归遍历功能。

import glob as gbpath = gb.glob('d:\\2\\*')for path in path:print path

2.2,调用os.walk

遍历指定目录下的所有文件和文件夹,递归遍历,功能强大,推荐使用。

import osfor dirpath, dirnames, filenames in os.walk('d:\\2\\'):for file in filenames:fullpath = os.path.join(dirpath, file)print fullpath, file

2.3,自己DIY

遍历指定目录下的所有文件和文件夹,递归遍历,自主编写,扩展性强,可以学习练手。

import os; files = list(); def DirAll(pathName): if os.path.exists(pathName): fileList = os.listdir(pathName); for f in fileList: if f=="$RECYCLE.BIN" or f=="System Volume Information": continue; f=os.path.join(pathName,f); if os.path.isdir(f):DirAll(f); else: dirName=os.path.dirname(f); baseName=os.path.basename(f); if dirName.endswith(os.sep): files.append(dirName+baseName); else: files.append(dirName+os.sep+baseName); DirAll("D:\\2\\"); for f in files: print f# print f.decode('gbk').encode('utf-8');

2.4,备注

注意,如果遍历过程中,出现文件名称或文件路径乱码问题,可以查看本文的参考资料来解决。

3,转换Word文件为PDF

通过Windows Com组件(win32com),调用Word服务(Word.Application),实现Word到PDF文件的转换。因此,要求该Python程序需要在有Word服务(可能至少要求版本)的Windows机器上运行。

#coding:utf8import os, sysreload(sys)sys.setdefaultencoding('utf8')from win32com.client import Dispatch, constants, gencacheinput = 'D:\\2\\test\\11.docx'output = 'D:\\2\\test\\22.pdf'print 'input file', inputprint 'output file', output# enable python COM support for Word # 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(output):print 'translate success'else:print 'translate fail'

4,批量转换

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

# -*- coding:utf-8 -*-# doc2pdf.py: python script to convert doc to pdf with bookmarks!# Requires Office SP2# Requires python for win32 extensionimport glob as gbimport sysreload(sys)sys.setdefaultencoding('utf8')'''参考:/rumswell/article/details/7434302'''import sys, osfrom win32com.client import Dispatch, constants, gencache# from config import REPORT_DOC_PATH,REPORT_PDF_PATHREPORT_DOC_PATH = 'D:/2/doc/'REPORT_PDF_PATH = 'D:/2/doc/'# Word转换为PDFdef 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' % inputreturn 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' % inputreturn Falseif (not os.path.isabs(output)):os.chdir(REPORT_PDF_PATH)output = os.path.abspath(output)else:print u'%s not absolute path' % outputreturn Falsetry:print input, output# enable python COM support for Word # 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 Trueelse:print 'translate fail'return Falseexcept:print ' exception'return -1if __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 osfor dirpath, dirnames, filenames in os.walk(REPORT_DOC_PATH):for file in filenames:fullpath = os.path.join(dirpath, file)print fullpath, filerc = word2pdf(file.rstrip('.docx'))

5,参考资料

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

/rumswell/article/details/7434302Python 将word文件转换为PDF文件

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

/yongh701/article/details/46907383

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。