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:utf8import os, sys
reload(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', 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 extensionimport 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' % 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 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 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 2007的文档转为pdf文件
    http://blog.csdn.net/rumswell/article/details/7434302
  • Python 将word文件转换为PDF文件
    http://blog.csdn.net/lis_12/article/details/54603298
  • 遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题
    http://blog.csdn.net/yongh701/article/details/46907383

Python - 批量转换Word文件为PDF文件相关推荐

  1. python批量pdf转word,python批量实现Word文件转换为PDF文件

    本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下 1.目的 通过万能的Python把一个目录下的所有Word文件转换为PDF文件. 2.遍历目录 作者总 ...

  2. python批量操作word文档实战_python批量实现Word文件转换为PDF文件

    本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下 1.目的 通过万能的Python把一个目录下的所有Word文件转换为PDF文件. 2.遍历目录 作者总 ...

  3. Python+pywin32批量转换Word文件为PDF文件

    代码功能:把当前文件夹中多个Word文件批量转换为PDF文件 技术原理:代码实际上是调用了Word的"导出"功能,模拟了手工转换的操作并实现了自动化,要求已正确安装Python扩展 ...

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

    场景:有大批word文件需要转PDF,手动word转pdf速度很慢,尤其当word文件很大的时候,这时候就可以使用程序高效批量转换word文件了. 实现效果如下图所示 代码如下: #!user/bin ...

  5. Python批量实现Word、EXCLE、PPT转PDF文件

    一.绪论背景 在日常办公和文档处理中,有时我们需要将多个Word文档.Excel表格或PPT演示文稿转换为PDF文件.将文档转换为PDF格式的好处是它可以保留文档的布局和格式,并且可以在不同平台上进行 ...

  6. python编辑svg文件_使用Python批量转换SVG文件为PNG或PDF文件

    使用Python批量转换SVG文件为PNG或PDF文件 使用Python批量转换SVG文件为PNG或PDF文件 使用模块 1 模块单独使用 2 模块用于代码 实例 1 命令行方式 2 python脚本 ...

  7. 批量转换word(docx)为pdf文件

    在某度搜索到的"批量转换 Word 文档"很多都是挂着免费的旗号,实际还是收费或者限制文件转换数量的. 这里分享一个开源,完全免费,不用在线上传,而且不用安装的方案. 1. 保存脚 ...

  8. python完成文件夹批量word转pdf文件及pdf文件合并+word文件合并

    前言:有同学问我,如何把文件夹中的文件一次性完成打印,由于文件太多,单个打印着实麻烦.这些文件主要有三种类型,分别为PDF,word(.doc和.docx),我决定把他们全部变为PDF文件,然后再合并 ...

  9. Python批量提取Word文件题库中的答案

    问题描述:假设有Word文件"Python题库.docx"中有若干Python题目(目前有1000道,已在公众号内分享第一期1000道Python题库系列分享一(17道))和对应的 ...

最新文章

  1. Jenkins maven 编译一些问题
  2. java泛型数组替代方案_Kotlin泛型Array T导致“不能将T用作具体类型参数 . 使用类代替“但List T不会...
  3. keil2c语言使用教程,Keil教程(2)
  4. 易优cms后台RCE以及任意文件上传漏洞
  5. 《零基础看得懂的C++入门教程 》——(8)搞定二维数组与循环嵌套
  6. mybatis下log4j使用
  7. win10家庭版无法安装mysql_Win10安装MySQL
  8. oracle日期处理完全版
  9. html用图片链接网址
  10. 相位相关计算两张图片的平移量
  11. 时间戳服务器作用,使用时间戳给医院带来的好处
  12. 计算机显示器文字不清楚,笔记本电脑字体显示不清晰解决方法分辨率和显卡驱动...
  13. 一个计算机毕业生的求职经验
  14. Unity3D学习-角色跳起-落地
  15. 北京兄弟连web前端
  16. 卡罗拉 (COROLLA) - 雨刷/雨刮器频率控制
  17. NASA-VIIRS夜间灯光VNP46A2产品及批量下载
  18. 物联网专科专业必修课程_大专学物联网工程 物联网要学哪些课程
  19. 内卷起来,2023年外贸B2B企业怎么通过独立站吸引客户的注意
  20. 【对讲机的那点事】诚信护航,灵通LD-7900数字对讲机,业余无线电爱好者的终端产品...

热门文章

  1. 计算机著作权登记证书什么作用
  2. 学习——分布式文件系统 fastDFS
  3. 75 道 BAJT 中高级 Java 面试题,你能答上几道?
  4. NSI45025AT1G 25mA 45V LED驱动器,恒流调节器 工业指示灯、背光灯解决方案
  5. js中let使用时遇到的问题
  6. 当科大讯飞还在博鳌上刷存在感,搜狗已经准备好引领AI翻译机的下一波浪潮
  7. python小猪代码_代码绘制一只小猪佩奇---python篇
  8. Oracle 带有特殊符号的别名(如:/ , - 等)
  9. android的休眠
  10. 高手是这样调整PS画笔大小颜色硬度的,你会吗