pythonpdf-generationdocxcomtypes

Why does doc.Close() stop further code from running?


Trying to make a converter from a docx to pdf in python, expecting a response on the front end when it finishes but doc.Close() either exits or runs indefinitely. Any idea how to fix this?

I currently have this, no exceptions have been raised, program hasn't crashed, no timeout, nor a traceback. PDF gets made successfully but print and finally statement does not happen

import comtypes.client
import os

doc_path = "absPath\to\document.docx"
pdf_path = "absPath\to\save\location.pdf"

try:
   # Initialize Word application using COM interface
   word = comtypes.client.CreateObject("Word.Application")
   word.Visible = False
   word.DisplayAlerts = 0  # 0 suppresses all alerts, including Save As dialogs
   # Save the document as PDF
   doc = word.Documents.Open(doc_path)
   doc.SaveAs(pdf_path, FileFormat=17) # FileFormat=17 is for PDF
   doc.Close() # Close the document

   print(f"Document saved as PDF: {pdf_path}")

except Exception as e:
   print(f"An error occurred during conversion: {e}")

finally:
   # Quit Word application
   word.Quit()
   return pdf_path

Solution

  • Possibly found the answer. The save as dialouge box came up due to me not setting SaveChanges=False

    in doc.Close()

    meaning the fix would be

    doc.Close(SaveChanges=False)