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之关于循环的小伎俩
Oct 02 Python
Python中使用Inotify监控文件实例
Feb 14 Python
Python编程中的for循环语句学习教程
Oct 14 Python
Python爬虫爬取一个网页上的图片地址实例代码
Jan 16 Python
Python基于递归算法求最小公倍数和最大公约数示例
Jul 27 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
python 去除二维数组/二维列表中的重复行方法
Jan 23 Python
python 动态迁移solr数据过程解析
Sep 04 Python
python实现字典嵌套列表取值
Dec 16 Python
python numpy生成等差数列、等比数列的实例
Feb 25 Python
记一次django内存异常排查及解决方法
Aug 07 Python
python flask框架快速入门
May 14 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 cli模式学习(PHP命令行模式)
2013/06/03 PHP
php通过文件头判断格式的方法
2016/05/28 PHP
基于PHP实现短信验证码接口(容联运通讯)
2016/09/06 PHP
ThinkPHP实现附件上传功能
2017/04/27 PHP
PHP注释语法规范与命名规范详解篇
2018/01/21 PHP
php高性能日志系统 seaslog 的安装与使用方法分析
2020/02/29 PHP
借用Google的Javascript API Loader来加速你的网站
2009/01/28 Javascript
javaScript如何生成xmlhttp
2013/12/16 Javascript
自写的jQuery异步加载数据添加事件
2014/05/15 Javascript
jQuery购物网页经典制作案例
2016/08/19 Javascript
JS表格组件BootstrapTable行内编辑解决方案x-editable
2016/09/01 Javascript
web 屏蔽BackSpace键实例代码
2016/12/24 Javascript
jQuery实现遮罩层登录对话框
2016/12/29 Javascript
nodejs multer实现文件上传与下载
2017/05/10 NodeJs
基于vue组件实现猜数字游戏
2020/05/28 Javascript
JavaScript通过mouseover()实现图片变大效果的示例
2017/12/20 Javascript
layui select动态添加option的实例
2018/03/07 Javascript
详解vue填坑之解决部分浏览器不支持pushState方法
2018/07/12 Javascript
vue实现引入本地json的方法分析
2018/07/12 Javascript
详解vue移动端项目的适配(以mint-ui为例)
2018/08/17 Javascript
微信小程序使用for循环动态渲染页面操作示例
2018/12/25 Javascript
微信小程序实现单列下拉菜单效果
2019/04/25 Javascript
详解vue beforeRouteEnter 异步获取数据给实例问题
2019/08/09 Javascript
vue 验证码界面实现点击后标灰并设置div按钮不可点击状态
2019/10/28 Javascript
javascript实现前端分页功能
2020/11/26 Javascript
[01:59]游戏“zheng”当时试玩会
2019/08/21 DOTA
python根据京东商品url获取产品价格
2015/08/09 Python
Python实现删除列表中满足一定条件的元素示例
2017/06/12 Python
Python实现的凯撒密码算法示例
2018/04/12 Python
python中return的返回和执行实例
2019/12/24 Python
如何在Anaconda中打开python自带idle
2020/09/21 Python
美国婚礼礼品网站:MyWeddingFavors
2018/09/26 全球购物
戴森英国官网:Dyson英国
2019/05/07 全球购物
伦敦奥运会的口号
2014/06/21 职场文书
医学检验专业自荐信
2014/09/18 职场文书
员工2014年度工作总结
2014/12/09 职场文书