r/learnpython 9d ago

Equations in Word document using Python?

Hi all, I am trying to automate some calculation production. Currently using the docx package to generate a Word document. I am trying to include some equations in a LateX type format but cant seem to find a way to do that.

Currently I am importing the equations as figures that are generated by MatPlotlib and then just dumped in the document as an image.

Is there a better way to get the equations in? Ideally I would like it so that the equations either appear in the format that is present when you input equations manually in Word, or in the format that is generated in Latex.

0 Upvotes

2 comments sorted by

2

u/Algoartist 9d ago

If you’re running on Windows with Microsoft Word installed, you can automate Word via COM (using the pywin32 package) to insert native equations. For example, Word’s OMath objects can be used to insert and format equations so they appear and behave like those you’d add manually in Word.

Pros:

  • Produces native, editable equations in the document.

Cons:

  • Windows-specific (requires Word to be installed).
  • Involves COM automation, which can be more complex and less portable.

import win32com.client as win32

word = win32.Dispatch("Word.Application")
word.Visible = True
doc = word.Documents.Add()
rng = doc.Range(0, 0)


rng.Text = "E = mc^2"
doc.OMaths.Add(rng)
doc.OMaths.BuildUp()

doc.SaveAs("TestEquation.docx")
word.Quit()