python批量實現Word檔案轉換為PDF檔案,

來源:互聯網
上載者:User

python批量實現Word檔案轉換為PDF檔案,

本文為大家分享了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檔案

遍曆某目錄下的所有檔案夾與檔案的路徑、輸出中文亂碼問題

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.