我有一个使用python docx模块生成的docx对象。我怎样才能直接将其转换为pdf?
答案 0 :(得分:0)
以下内容适用于安装了Word的计算机(我认为Word 2007及更高版本,但不建议我这样做)。我不确定这是否适用于所有内容,但似乎对我适用于doc,docx和.rtf文件。我认为它应该适用于Word可以打开的所有文件。
# Imports =============================================================
import comtypes.client
import time
# Variables and Inputs=================================================
File = r'C:\path\filename.docx' # Or .doc, rtf files
outFile = r'C:\path\newfilename.pdf'
# Functions ============================================================
def convert_word_to_pdf(inputFile,outputFile):
''' the following lines that are commented out are items that others shared with me they used when
running loops to stop some exceptions and errors, but I have not had to use them yet (knock on wood) '''
word = comtypes.client.CreateObject('Word.Application')
#word.visible = True
#time.sleep(3)
doc = word.Documents.Open(inputFile)
doc.SaveAs(outputFile, FileFormat = 17)
doc.close()
#word.visible = False
word.Quit()
# Main Body=================================================================
convert_word_to_pdf(File,outFile)