python实现word 2007文档转换为pdf文件

yipeiwu_com6年前Python基础

在开发过程中,会遇到在命令行下将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 extension 
 
 
import sys, os 
from win32com.client import Dispatch, constants, gencache 
 
def 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 -1 
 
if __name__=='__main__': 
  rc = main() 
  if rc: 
    sys.exit(rc) 
  sys.exit(0) 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

深入解答关于Python的11道基本面试题

深入解答关于Python的11道基本面试题

前言 本文给大家深入的解答了关于Python的11道基本面试题,通过这些面试题大家能对python进一步的了解和学习,下面话不多说,来看看详细的介绍吧。 一、单引号,双引号,三引号的区...

selenium+python截图不成功的解决方法

selenium+python,使用webdriver的截图函数get_screenshot_as_file()截图,代码如下: from selenium import webdr...

python实现文本文件合并

python合并文本文件示例代码。 python实现两个文本合并 employee文件中记录了工号和姓名 cat employee.txt: 100 Jason Smith 20...

在Python的Flask中使用WTForms表单框架的基础教程

在Python的Flask中使用WTForms表单框架的基础教程

下载和安装 安装 WTForms 最简单的方式是使用 easy_install 和 pip: easy_install WTForms # or pip install WTForm...

python去除扩展名的实例讲解

获取不带扩展名的文件的名称: import os printos.path.splitext("path_to_file")[0] from os.path import ba...