使用python将rtf转换为pdf

时间:2015-04-14 21:21:31

标签: python pdf rtf

我是python语言的新手,我有一个任务是使用python将rtf转换为pdf。我用谷歌搜索并找到了一些代码 - (不完全是rtf到pdf)但我尝试了它并根据我的要求改变了它。但我无法解决它。

我使用了以下代码:

import sys
import os
import comtypes.client
#import win32com.client
rtfFormatPDF = 17

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

rtf= comtypes.client.CreateObject('Rtf.Application')

rtf.Visible = True
doc = rtf.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=rtfFormatPDF)
doc.Close()
rtf.Quit()

但它抛出以下错误

Traceback (most recent call last):
  File "C:/Python34/Lib/idlelib/rtf_to_pdf.py", line 12, in <module>
    word = comtypes.client.CreateObject('Rtf.Application')
  File "C:\Python34\lib\site-packages\comtypes\client\__init__.py", line 227, in CreateObject
    clsid = comtypes.GUID.from_progid(progid)
  File "C:\Python34\lib\site-packages\comtypes\GUID.py", line 78, in from_progid
    _CLSIDFromProgID(str(progid), byref(inst))
  File "_ctypes/callproc.c", line 920, in GetResult
OSError: [WinError -2147221005] Invalid class string

任何人都可以帮我吗? 如果有人能找到更好,更快的方法,我真的很感激。我有大约200,000个文件要转换。

Anisha

2 个答案:

答案 0 :(得分:4)

我使用了Marks的建议并将其更改回Word.Application并将我的源指向rtf文件。完美的工作! - 这个过程很慢,但仍然比我的团队使用的JAVA应用程序更快。我在我的问题中附上了最终的代码。

最终守则: 使用与Word应用程序一起使用的代码完成了它:

import sys
import os,os.path
import comtypes.client

wdFormatPDF = 17

input_dir = 'input directory'
output_dir = 'output directory'

for subdir, dirs, files in os.walk(input_dir):
    for file in files:
        in_file = os.path.join(subdir, file)
        output_file = file.split('.')[0]
        out_file = output_dir+output_file+'.pdf'
        word = comtypes.client.CreateObject('Word.Application')

        doc = word.Documents.Open(in_file)
        doc.SaveAs(out_file, FileFormat=wdFormatPDF)
        doc.Close()
        word.Quit()

答案 1 :(得分:0)

如果您的系统中装有Libre Office,那么您将获得最佳解决方案。

import os
os.system('soffice --headless --convert-to pdf filename.rtf')
# os.system('libreoffice --headless -convert-to pdf filename.rtf')
# os.system('libreoffice6.3 --headless -convert-to pdf filename.rtf')

命令可能会因版本和平台而异。但这将是我有史以来最好的解决方案。

相关问题