python批量实现Word文件转换为PDF文件
2018-03-15 11:38
1526 查看
本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下
1、目的
通过万能的Python把一个目录下的所有Word文件转换为PDF文件。
2、遍历目录
作者总结了三种遍历目录的方法,分别如下。
2.1.调用glob
遍历指定目录下的所有文件和文件夹,不递归遍历,需要手动完成递归遍历功能。
import glob as gb path = gb.glob('d:\\2\\*') for path in path: print path
2.2.调用os.walk
遍历指定目录下的所有文件和文件夹,递归遍历,功能强大,推荐使用。
import os for 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服务(可能至少要求2007版本)的Windows机器上运行。
#coding:utf8 import os, sys reload(sys) sys.setdefaultencoding('utf8') from win32com.client import Dispatch, constants, gencache input = 'D:\\2\\test\\11.docx' output = 'D:\\2\\test\\22.pdf' print 'input file', input print 'output file', 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(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 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实现合并同一个文件夹下所有PDF文件的方法示例
- 用C#实现pdf文件的完整性验证
- lecene.net实现pdf,doc,xls,ppt,htm,html等格式文件的检索
- java实现爬虫技术,读取txt,word,excel,ppt,pdf,html等格式的文件
- 【C#功能实现】c#程序为PDF文件填写表单内容
- 用jspdf实现页面下载生成pdf文件
- Java程序员从笨鸟到菜鸟之(一百零五)java操作office和pdf文件(三)利用jxl实现数据导出excel报表以及与POI的区别
- java集成pdf.js实现pdf文件在线预览
- 在你的网页中嵌入PDF等文件,实现pdf在线阅读
- Java平台要实现类似豆丁百度文科的文档在线阅读,总体思路是讲doc docx等文件格式利用jcom转换成pdf再用swftools转为swf。再用flexpaper组件显示swf。
- html中实现添加水印的功能 / 在jsp页面上直接打开PDF文件
- 简单的jQuery.jqprint插件实现打印HTML页面,页面导出为PDF文件
- Itext+JSOUP实现可自定义样式的PDF文件
- java实现pdf文件截图的方法【附PDFRenderer.jar下载】
- C#实现PDF文件添加图片背景
- 通过Aspose对Word,Excel文件进行Pdf转换,实现在线预览
- 【C#功能实现】C# 输出pdf文件流在页面上显示
- .NET实现对服务器端目录下PDF文件的预览
- Asp.Net实现生成WORD或PDF文件