简体   繁体   中英

What is the best way to convert a docx object to a pdf in python

I have a docx object generated using the python docx module. How would I be able to convert it to pdf directly?

The following works for computers that have word installed (I think word 2007 and above, but do not hold me to that). I am not sure this works on everything but it seems to work for me on doc, docx, and .rtf files. I think it should work on all files that word can open.

# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM