pythonpdfautomationms-wordwin32com

Convert .doc files to pdf using python COM interface to Microsoft Word


How can I convert a Word document in PDF by calling the Word COM interface from Python?


Solution

  • A simple example using comtypes, converting a single file, input and output filenames given as commandline arguments:

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

    You could also use pywin32, which would be the same except for:

    import win32com.client
    

    and then:

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