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


Posted in Python onMarch 15, 2018

本文为大家分享了python批量转换Word文件为PDF文件的具体方法,供大家参考,具体内容如下

1、目的

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

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 相关文章推荐
Python中让MySQL查询结果返回字典类型的方法
Aug 22 Python
利用Python的Django框架生成PDF文件的教程
Jul 22 Python
日常整理python执行系统命令的常见方法(全)
Oct 22 Python
运用Python的webbrowser实现定时打开特定网页
Feb 21 Python
python进阶之自定义可迭代的类
Aug 20 Python
Python单元测试与测试用例简析
Nov 09 Python
通过实例解析python描述符原理作用
Jan 22 Python
Python填充任意颜色,不同算法时间差异分析说明
May 16 Python
python基于socket函数实现端口扫描
May 28 Python
Flask缓存静态文件的具体方法
Aug 02 Python
python接口自动化框架实战
Dec 23 Python
python实现简单石头剪刀布游戏
Oct 24 Python
python实现求解列表中元素的排列和组合问题
Mar 15 #Python
Python遍历某目录下的所有文件夹与文件路径
Mar 15 #Python
Python cookbook(数据结构与算法)找出序列中出现次数最多的元素算法示例
Mar 15 #Python
ubuntu安装sublime3并配置python3环境的方法
Mar 15 #Python
Centos7 Python3下安装scrapy的详细步骤
Mar 15 #Python
python实现word 2007文档转换为pdf文件
Mar 15 #Python
python中使用PIL制作并验证图片验证码
Mar 15 #Python
You might like
法国:浪漫之都的咖啡文化
2021/03/03 咖啡文化
phpfans留言版用到的install.php
2007/01/04 PHP
header中Content-Disposition的作用与使用方法
2012/06/13 PHP
使用php+apc实现上传进度条且在IE7下不显示的问题解决方法
2013/04/25 PHP
一个简单的php加密解密函数(动态加密)
2013/06/19 PHP
经典PHP加密解密函数Authcode()修复版代码
2015/04/05 PHP
PHP基于yii框架实现生成ICO图标
2015/11/13 PHP
PHP实现的mongoDB数据库操作类完整实例
2018/04/10 PHP
showModalDialog 和 showModelessDialog
2007/01/22 Javascript
innertext , insertadjacentelement , insertadjacenthtml , insertadjacenttext 等区别
2007/06/29 Javascript
jquery里的each使用方法详解
2010/12/22 Javascript
javascript实现相同事件名称,不同命名空间的调用方法
2015/06/26 Javascript
纯js仿淘宝京东商品放大镜功能
2017/03/02 Javascript
jQuery EasyUI的TreeGrid查询功能实现方法
2017/08/08 jQuery
bootstrap轮播模板使用方法详解
2017/11/17 Javascript
在vue中使用css modules替代scroped的方法
2018/03/10 Javascript
小程序图片剪裁加旋转的示例代码
2018/07/10 Javascript
基于vue-router 多级路由redirect 重定向的问题
2018/09/03 Javascript
使用watch在微信小程序中实现全局状态共享
2019/06/03 Javascript
layui实现数据表格自定义数据项
2019/10/26 Javascript
在Python中的Django框架中进行字符串翻译
2015/07/27 Python
Python使用email模块对邮件进行编码和解码的实例教程
2016/07/01 Python
深入理解Python单元测试unittest的使用示例
2017/11/18 Python
如何在Django中设置定时任务的方法示例
2019/01/18 Python
matlab中imadjust函数的作用及应用举例
2020/02/27 Python
如何使用Python处理HDF格式数据及可视化问题
2020/06/24 Python
python des,aes,rsa加解密的实现
2021/01/16 Python
python中的插入排序的简单用法
2021/01/19 Python
Champion澳大利亚官网:美国冠军运动服装
2018/05/07 全球购物
什么是GWT的Module
2013/01/20 面试题
小区消防演习方案
2014/02/21 职场文书
弘扬雷锋精神演讲稿
2014/05/10 职场文书
开展创先争优活动总结
2014/08/28 职场文书
学生考试舞弊检讨书
2015/01/01 职场文书
2015年大学教师工作总结
2015/05/20 职场文书
毛主席纪念堂观后感
2015/06/17 职场文书