利用Python將word 2007的文檔轉為pdf檔案__Python

來源:互聯網
上載者:User

在開發過程中,會遇到在命令列下將DOC文檔(或者是其他Office文檔)轉換為PDF的要求。比如在項目中如果手冊是DOC格式的,在項目發布時希望將其轉換為PDF格式,並且保留DOC中的書籤,連結等。將該過程整合到構建過程中就要求命令列下進行轉換。
Michael Suodenjoki展示了使用Office的COM介面進行命令列下的轉換。但其匯出的PDF文檔沒有書籤。在Office 2007 SP2中,微軟加入了該功能,對應的介面是ExportAsFixedFormat。該方法不僅適用於Word,而且也適用於Excel。
面是一個簡單的Python指令碼來展示如何轉換DOC為PDF。該指令碼需要Office 2007 SP2, Python 2.6與Python for win32(使Python能調用COM)。這裡也可以使用其他支援COM的語言。ExportAsFixedFormat還有其他一些參數,具體參見MSDN相關文檔。需要注意的是文檔路徑需要為絕對路徑,因為Word啟動後當前路徑不是呼叫指令碼時的當前路徑。

#-*- coding:utf-8 -*-# doc2pdf.py: python script to convert doc to pdf with bookmarks!# Requires Office 2007 SP2# Requires python for win32 extensionimport sys, osfrom win32com.client import Dispatch, constants, gencachedef doc2pdf(input, output):  w = Dispatch("Word.Application")  try:    doc = w.Documents.Open(input, ReadOnly = 1)    doc.ExportAsFixedFormat(output, constants.wdExportFormatPDF,       Item = constants.wdExportDocumentWithMarkup, CreateBookmarks = constants.wdExportCreateHeadingBookmarks)    return 0  except:    return 1  finally:    w.Quit(constants.wdDoNotSaveChanges)# Generate all the support we can.def GenerateSupport():  # 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)def main():  if (len(sys.argv) == 2):    input = sys.argv[1]    output = os.path.splitext(input)[0]+'.pdf'  elif (len(sys.argv) == 3):    input = sys.argv[1]    output = sys.argv[2]  else:    input = u'BA06007013.docx'#word文檔的名稱    output = u'BA06007013.pdf'#pdf文檔的名稱  if (not os.path.isabs(input)):    input = os.path.abspath(input)  if (not os.path.isabs(output)):    output = os.path.abspath(output)  try:    GenerateSupport()    rc = doc2pdf(input, output)    return rc  except:    return -1if __name__=='__main__':rc = main()if rc:sys.exit(rc)sys.exit(0)


 

試一試,還真不錯,比Adobe的軟體效果還好!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.