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获取一组数据里最大值max函数用法实例
May 26 Python
Python实现简单登录验证
Apr 13 Python
Python算法应用实战之队列详解
Feb 04 Python
使用python画个小猪佩奇的示例代码
Jun 06 Python
使用python根据端口号关闭进程的方法
Nov 06 Python
Python3.4学习笔记之类型判断,异常处理,终止程序操作小结
Mar 01 Python
python面试题小结附答案实例代码
Apr 11 Python
python接口自动化(十六)--参数关联接口后传(详解)
Apr 16 Python
python利用百度云接口实现车牌识别的示例
Feb 21 Python
浅谈Python中range与Numpy中arange的比较
Mar 11 Python
详解Django中 render() 函数的使用方法
Apr 22 Python
Python中的pprint模块
Nov 27 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
PHP CURL模拟登录新浪微博抓取页面内容 基于EaglePHP框架开发
2012/01/16 PHP
如何使用php判断所处服务器操作系统的类型
2013/06/20 PHP
PHP递归统计系统中代码行数
2019/09/19 PHP
jquery图片放大镜功能的实例代码
2013/03/26 Javascript
javascript轻松实现当鼠标移开时已弹出子菜单自动消失
2013/12/29 Javascript
jQuery Trim去除字符串首尾空字符的实现方法说明
2014/02/11 Javascript
Javascript的setTimeout()使用闭包特性时需要注意的问题
2014/09/23 Javascript
jquery插件pagination实现无刷新ajax分页
2015/09/30 Javascript
javascript超过容器后显示省略号效果的方法(兼容一行或者多行)
2016/07/14 Javascript
Vue.js@2.6.10更新内置错误处机制Fundebug同步支持相应错误监控
2019/05/13 Javascript
layui 根据后台数据动态创建下拉框并同时默认选中的实例
2019/09/02 Javascript
js中!和!!的区别与用法
2020/05/09 Javascript
将图片文件嵌入到wxpython代码中的实现方法
2014/08/11 Python
Python安装第三方库及常见问题处理方法汇总
2016/09/13 Python
对Python3中的print函数以及与python2的对比分析
2018/05/02 Python
使用Python批量修改文件名的代码实例
2019/01/24 Python
举例讲解Python常用模块
2019/03/08 Python
python 实现创建文件夹和创建日志文件的方法
2019/07/07 Python
PIL图像处理模块paste方法简单使用详解
2019/07/17 Python
Python3批量移动指定文件到指定文件夹方法示例
2019/09/02 Python
Python实现图片裁剪的两种方式(Pillow和OpenCV)
2019/10/30 Python
HTML5中的Web Notification桌面通知功能的实现方法
2019/07/29 HTML / CSS
英国床垫在线:Mattress Online
2016/12/07 全球购物
全球游戏Keys和卡片市场:GamesDeal
2018/03/28 全球购物
俄罗斯香水和化妆品购物网站:Л’Этуаль
2018/05/10 全球购物
汽车维修专业毕业生的求职信分享
2013/12/04 职场文书
自我评价格式
2014/01/06 职场文书
趣味比赛活动方案
2014/02/15 职场文书
初中生期末评语大全
2014/04/24 职场文书
行政专员岗位职责说明书
2014/07/30 职场文书
2014迎国庆标语大全
2014/09/19 职场文书
企业党员个人自我评价
2014/09/20 职场文书
优秀党员申报材料
2014/12/18 职场文书
培训班通知
2015/04/25 职场文书
交通处罚决定书
2015/06/24 职场文书
httpclient调用远程接口的方法
2022/08/14 Java/Android