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实例之wxpython中Frame使用方法
Jun 09 Python
12步教你理解Python装饰器
Feb 25 Python
修改python plot折线图的坐标轴刻度方法
Dec 13 Python
Python3.5内置模块之time与datetime模块用法实例分析
Apr 27 Python
Python 运行.py文件和交互式运行代码的区别详解
Jul 02 Python
30秒学会30个超实用Python代码片段【收藏版】
Oct 15 Python
python 中值滤波,椒盐去噪,图片增强实例
Dec 18 Python
python3实现往mysql中插入datetime类型的数据
Mar 02 Python
利用python对excel中一列的时间数据更改格式操作
Jul 14 Python
python 使用cycle构造无限循环迭代器
Dec 02 Python
深度学习tensorflow基础mnist
Apr 14 Python
详解MindSpore自定义模型损失函数
Jun 30 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 if 想到的些问题
2008/03/22 PHP
php fckeditor 调用的函数
2009/06/21 PHP
详解ThinkPHP3.2.3验证码显示、刷新、校验
2016/12/29 PHP
微信第三方登录(原生)demo【必看篇】
2017/05/26 PHP
PHP实现mysqli批量执行多条语句的方法示例
2017/07/22 PHP
PHP 7.4 新语法之箭头函数实例详解
2019/05/09 PHP
jquery插件 cluetip 关键词注释
2010/01/12 Javascript
jquery入门—访问DOM对象方法
2013/01/07 Javascript
JS网页播放声音实现代码兼容各种浏览器
2013/09/22 Javascript
推荐6款基于jQuery实现图片效果插件
2014/12/07 Javascript
javascript实现画不相交的圆
2015/04/07 Javascript
打造自己的jQuery插件入门教程
2016/09/23 Javascript
bootstrap table小案例
2016/10/21 Javascript
Javascript 引擎工作机制详解
2016/11/30 Javascript
js实现仿购物车加减效果
2017/03/01 Javascript
vue中过滤器filter的讲解
2019/01/21 Javascript
使用weixin-java-miniapp配置进行单个小程序的配置详解
2019/03/29 Javascript
vue-cli 3.x配置跨域代理的实现方法
2019/04/12 Javascript
解决Layui数据表格显示无数据提示的问题
2019/11/14 Javascript
Vue 数据响应式相关总结
2021/01/28 Vue.js
[01:54]TI4西雅图DOTA2选手欢迎晚宴 现场报道
2014/07/08 DOTA
[47:42]完美世界DOTA2联赛PWL S2 GXR vs Ink 第一场 11.19
2020/11/20 DOTA
Python黑帽编程 3.4 跨越VLAN详解
2016/09/28 Python
对python GUI实现完美进度条的示例详解
2018/12/13 Python
python实现字符串完美拆分split()的方法
2019/07/16 Python
python绘制BA无标度网络示例代码
2019/11/21 Python
python中翻译功能translate模块实现方法
2020/12/17 Python
美国隐形眼镜网上商店:Lens.com
2019/09/03 全球购物
汽车维修与检测专业应届生求职信
2013/11/12 职场文书
2013届毕业生求职信范文
2013/11/20 职场文书
十八大闭幕感言
2014/01/22 职场文书
四年级下册教学反思
2014/02/01 职场文书
读群众路线心得体会
2014/03/07 职场文书
超市七夕促销活动方案
2014/08/28 职场文书
老公婚前保证书
2015/02/28 职场文书
创业计划书之健康营养产业
2019/10/15 职场文书