dummytaurus 发表于 2010-01-16 20:03

命令行下将DOC文档转换为PDF


                  在开发过程中,会遇到在命令行下将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启动后当前路径不是调用脚本时的当前路径。#################################################################
# doc2pdf.py: python script to convert doc to pdf with
# Requires Office 2007 SP2
# Requires python for win32 extension
#
# Author: Huang Zhan
# Date: 2010-01-05
#
# Usage: doc2pdf.py input
#
import sys, os
from win32com.client import Dispatch, constants, gencache
def usage():
    sys.stderr.write ("doc2pdf.py input ")
    sys.exit(2)
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
    output = os.path.splitext(input)+'.pdf'
elif (len(sys.argv) == 3):
    input = sys.argv
    output = sys.argv
else:
    usage()
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)
/fileicon/zip.gif
       
        文件:doc2pdf.zip
        大小:0KB
        下载:
下载
       
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/93573/showart_2150909.html

x140928 发表于 2014-09-28 20:04

pdf转换成word软件免费下载http://soft.hao123.com/soft/appid/16835.html
页: [1]
查看完整版本: 命令行下将DOC文档转换为PDF