2011-05-15 105 views
18

我的任务是将大量的.doc文件转换为.pdf。我的主管希望我这样做的唯一方法是通过MSWord 2010.我知道我应该能够使用python COM自动化实现自动化。唯一的问题是我不知道如何以及从哪里开始。我试图寻找一些教程,但无法找到任何(可能我可能有,但我不知道我在找什么)。.doc to pdf using python

现在我正在阅读通过this。不知道这将是多么有用。

回答

39

使用comtypes,转换单个文件一个简单的例子,输入和输出的文件名给出命令行参数:

import sys 
import os 
import comtypes.client 

wdFormatPDF = 17 

in_file = os.path.abspath(sys.argv[1]) 
out_file = os.path.abspath(sys.argv[2]) 

word = comtypes.client.CreateObject('Word.Application') 
doc = word.Documents.Open(in_file) 
doc.SaveAs(out_file, FileFormat=wdFormatPDF) 
doc.Close() 
word.Quit() 

也可以使用pywin32,这将是除了同一对:

import win32com.client 

然后:

word = win32com.client.Dispatch('Word.Application') 
+2

这正是我一直在寻找的。谢谢:) – nik 2011-05-17 21:02:18

+3

对于许多文件,考虑设置:'word.Visible = FALSE'救我已经成功地得到了这个词的文件的时间和处理(MS字不会显示这种方式,代码将在后台运行的本质) – ecoe 2014-04-10 14:09:48

+0

这为PowerPoint文件工作。使用'Powerpoint.Application','Presentations.Open'和'FileFormat = 32'。 – Snorfalorpagus 2015-03-25 13:39:22

2

如果您不介意使用PowerShell看看这个Hey, Scripting Guy! article。所提供的代码可以采用wdFormatPDF枚举值WdSaveFormat(请参阅here)。 This blog article提出了相同想法的不同实现。

+1

我是Linux/Unix用户,更倾向于Python。但ps脚本看起来很简单,正是我所期待的。谢谢:) – nik 2011-05-15 21:44:11

-3

我会建议忽略你的主管,并使用OpenOffice,它有一个Python API。 OpenOffice内置了对Python的支持,并且有人为此创建了一个特定库(PyODConverter)。

如果他对输出不满意,告诉他可能需要几个星期才能完成。

0

您应该从调查所谓的虚拟PDF打印驱动程序开始。 只要你找到一个你应该能够写入批处理文件,打印您的DOC文件到PDF文件。您可能也可以在Python中执行此操作(设置打印机驱动程序输出并在MSWord中发出文档/打印命令,稍后可以使用命令行AFAIR完成)。

2

unoconv用python写)和openoffice作为无头守护进程运行。 http://dag.wiee.rs/home-made/unoconv/

适用于doc,docx,ppt,pptx,xls,xlsx。 非常有用,如果你需要转换文档或保存/转换为服务器上的某些格式

2

我已经在这个问题上工作了半天,所以我想我应该分享一些我在这个问题上的经验。史蒂文的回答是正确的,但它会在我的电脑上失败。有两个关键点需要在此修复:

(1)。第一次创建'Word.Application'对象时,我应该在打开任何文档之前将它(app这个词)显示出来。 (实际上,即使我自己也无法解释为什么这会起作用,如果我不在计算机上这样做,当我试图在不可见模型中打开一个文档时,程序会崩溃,那么'Word.Application'对象将被删除OS)。

(2)。做完(1)之后,该程序有时会运行良好,但可能经常失败。崩溃错误"COMError: (-2147418111, 'Call was rejected by callee.', (None, None, None, 0, None))"意味着COM服务器可能无法很快响应。所以我在尝试打开文档之前添加了一段延迟。

做这两个步骤后,程序将完全无故障工作了。演示代码如下。如果遇到同样的问题,请尝试遵循以下两个步骤。希望能帮助到你。

import os 
    import comtypes.client 
    import time 


    wdFormatPDF = 17 


    # absolute path is needed 
    # be careful about the slash '\', use '\\' or '/' or raw string r"..." 
    in_file=r'absolute path of input docx file 1' 
    out_file=r'absolute path of output pdf file 1' 

    in_file2=r'absolute path of input docx file 2' 
    out_file2=r'absolute path of outputpdf file 2' 

    # print out filenames 
    print in_file 
    print out_file 
    print in_file2 
    print out_file2 


    # create COM object 
    word = comtypes.client.CreateObject('Word.Application') 
    # key point 1: make word visible before open a new document 
    word.Visible = True 
    # key point 2: wait for the COM Server to prepare well. 
    time.sleep(3) 

    # convert docx file 1 to pdf file 1 
    doc=word.Documents.Open(in_file) # open docx file 1 
    doc.SaveAs(out_file, FileFormat=wdFormatPDF) # conversion 
    doc.Close() # close docx file 1 
    word.Visible = False 
    # convert docx file 2 to pdf file 2 
    doc = word.Documents.Open(in_file2) # open docx file 2 
    doc.SaveAs(out_file2, FileFormat=wdFormatPDF) # conversion 
    doc.Close() # close docx file 2 
    word.Quit() # close Word Application 
1

我试过接受的答案,但并不是特别热衷于臃肿的PDF文件正在产生,这通常是比预期的数量级更大的数量级。寻找如何使用虚拟PDF打印机时,禁用对话框后,我碰到的BullZip PDF打印机,我已经相当深刻的印象,它的特点。现在它已被我以前使用的其他虚拟打印机取代。你会在他们的下载页面找到一个“免费社区版”。

可以找到COM API here并且可以找到可用设置的列表here。这些设置被写入一个“runonce”文件,该文件仅用于一个打印作业,然后自动删除。在打印多个PDF时,我们需要确保一个打印作业完成后再启动另一个打印作业,以确保每个文件的设置都正确使用。

import os, re, time, datetime, win32com.client 

def print_to_Bullzip(file): 
    util = win32com.client.Dispatch("Bullzip.PDFUtil") 
    settings = win32com.client.Dispatch("Bullzip.PDFSettings") 
    settings.PrinterName = util.DefaultPrinterName  # make sure we're controlling the right PDF printer 

    outputFile = re.sub("\.[^.]+$", ".pdf", file) 
    statusFile = re.sub("\.[^.]+$", ".status", file) 

    settings.SetValue("Output", outputFile) 
    settings.SetValue("ConfirmOverwrite", "no") 
    settings.SetValue("ShowSaveAS", "never") 
    settings.SetValue("ShowSettings", "never") 
    settings.SetValue("ShowPDF", "no") 
    settings.SetValue("ShowProgress", "no") 
    settings.SetValue("ShowProgressFinished", "no")  # disable balloon tip 
    settings.SetValue("StatusFile", statusFile)   # created after print job 
    settings.WriteSettings(True)      # write settings to the runonce.ini 
    util.PrintFile(file, util.DefaultPrinterName)  # send to Bullzip virtual printer 

    # wait until print job completes before continuing 
    # otherwise settings for the next job may not be used 
    timestamp = datetime.datetime.now() 
    while((datetime.datetime.now() - timestamp).seconds < 10): 
     if os.path.exists(statusFile) and os.path.isfile(statusFile): 
      error = util.ReadIniString(statusFile, "Status", "Errors", '') 
      if error != "0": 
       raise IOError("PDF was created with errors") 
      os.remove(statusFile) 
      return 
     time.sleep(0.1) 
    raise IOError("PDF creation timed out")