本文為大家分享了python批量轉換Word文件為PDF文件的具體方法,供大家參考,具體內容如下
1、目的
通過萬能的Python把一個目錄下的所有Word文件轉換為PDF文件。

2、遍歷目錄
作者總結了三種遍歷目錄的方法,分別如下。
2.1.調用glob
遍歷指定目錄下的所有文件和文件夾,不遞歸遍歷,需要手動完成遞歸遍歷功能。
import glob as gbpath = gb.glob('d://2//*')for path in path: print path2.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, file2.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'
新聞熱點
疑難解答