Python批量将Word转换为PDF的实现方案
本文介绍如何使用Python批量将目录下的Word文档转换为PDF格式。核心步骤包括利用glob、os.walk或自定义函数遍历目录,并通过Windows COM组件调用Word服务进行转换。该方法要求运行环境为安装有Word(建议2007及以上)的Windows系统,文中提供了完整的遍历与转换代码示例。
Python批量Word转PDF实现方案
本文分享了使用Python批量将Word文件转换为PDF的具体实现方法,供读者参考。
转换目的与目录遍历方法
1、目的
利用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.备注
注意:如果在遍历过程中遇到文件名称或文件路径出现乱码的情况,可参考本文提供的参考资料进行解决。
Word转PDF转换原理与批量实现
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将word 2007的文档转为pdf文件
遍历某目录下的所有文件夹与文件的路径、输出中文乱码问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









