Python实现将DOC文档转换为PDF的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python实现将DOC文档转换为PDF的方法。分享给大家供大家参考。具体实现方法如下:

import sys, os
from win32com.client import Dispatch, constants, gencache
def usage():
  sys.stderr.write ("doc2pdf.py input [output]")
  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[1]
  output = os.path.splitext(input)[0]+'.pdf'
 elif (len(sys.argv) == 3):
  input = sys.argv[1]
  output = sys.argv[2]
 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)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python绘制3D图形

Python绘制3D图形

3D图形在数据分析、数据建模、图形和图像处理等领域中都有着广泛的应用,下面将给大家介绍一下如何使用python进行3D图形的绘制,包括3D散点、3D表面、3D轮廓、3D直线(曲线)以及3...

Python二叉树的遍历操作示例【前序遍历,中序遍历,后序遍历,层序遍历】

本文实例讲述了Python二叉树的遍历操作。分享给大家供大家参考,具体如下: # coding:utf-8 """ @ encoding: utf-8 @ author: lixia...

使用Python写一个贪吃蛇游戏实例代码

我在程序中加入了分数显示,三种特殊食物,将贪吃蛇的游戏逻辑写到了SnakeGame的类中,而不是在Snake类中。 特殊食物: 1.绿色:普通,吃了增加体型 2.红色:吃了减少体型 3....

python Django模板的使用方法(图文)

python Django模板的使用方法(图文)

模版基本介绍模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板...

pytorch实现mnist分类的示例讲解

torchvision包 包含了目前流行的数据集,模型结构和常用的图片转换工具。 torchvision.datasets中包含了以下数据集 MNIST COCO(用于图像标注和目标检测...