侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   208

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

1、目的

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

2、遍历目录

作者总结了三种遍历目录的方法,分别如下。

2.1.调用glob

遍历指定目录下的所有文件和文件夹,不递归遍历,需要手动完成递归遍历功能。

import glob as gbpath = gb.glob('d:\\2\\*')for path in path: print path

2.2.调用os.walk

遍历指定目录下的所有文件和文件夹,递归遍历,功能强大,推荐使用。

import osfor 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, sysreload(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', inputprint '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 gbimport sysreload(sys)sys.setdefaultencoding('utf8')'''参考:http://blog.csdn.net/rumswell/article/details/7434302'''import sys, osfrom win32com.client import Dispatch, constants, gencache# from config import REPORT_DOC_PATH,REPORT_PDF_PATHREPORT_DOC_PATH = 'D:/2/doc/'REPORT_PDF_PATH = 'D:/2/doc/'# Word转换为PDFdef 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 -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 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将word 2007的文档转为pdf文件

遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
    下一条:
    python实现求解列表中元素的排列和组合问题
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客