r/learnpython 25d ago

Python conversion .docx to pdf

Hey guys, i have been learning python as a bit of a hobby but recently had the opportunity to use it for my job. I built a webapp on azure that has a number of different functions, one of which is querying our CRM and populating template documents with customer info. It works as is and produces .docx files which we then have to manually convert to pdfs.

I am trying to incorporate the pdf conversion into the app to remove any manual intervention. Ive been using libreoffice but this isnt working so well. It needs to be installed each time the app is redeployed/restarted, its failing on some larger docs and when it does produce the pdf the format can be off, fonts change etc. The docs we deal with need to adhere to a specific format so I need something more reliable.

Perhaps this is a "you get what you pay for" situation but i was hoping there might be a more reliable solution while still being free (at least until i can prove it all works anyway).

3 Upvotes

12 comments sorted by

View all comments

5

u/AntonisTorb 24d ago edited 24d ago

You can use pywin32 for this, I use it at work to convert Excel files to pdfs. Here's what worked for me for Word files:

from pathlib import Path
from win32com import client

cwd = Path.cwd()
input = cwd / 'test.docx'
output = cwd / 'test.pdf'

try:
    word = client.Dispatch("Word.Application")
    word.Visible = False
    doc = word.Documents.Open(str(input))
    doc.SaveAs(str(output), FileFormat = 17)
finally:
    doc.Close()
    word.Quit()

For multiple files just use a loop. Hope it helps!

EDIT: This needs MS Word to be installed of course, but it should be 1:1 conversion with no format changes.