我是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()
Run Code Online (Sandbox Code Playgroud)
但它抛出以下错误
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
Run Code Online (Sandbox Code Playgroud)
谁能帮我这个?如果有人能找到更好,更快的方法,我真的很感激.我有大约200,000个文件要转换.
Anisha
我使用了 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()
Run Code Online (Sandbox Code Playgroud)