I’ve been trying to find the best way of transferring an equation from the Python sympy library into a LibreOffice formula object. I couldn’t find much on the Internet for this, so I’m documenting the results of my experiments here, in case it’s of any use to anyone, and in case anyone can suggest a better way of going about things!
The best I’ve come up with is…
import sympy.printing
import tkinter
def sp2lo(eqn, filename=None):
mml = sympy.printing.mathml(eqn, printer='presentation')
mml = mml.replace('<mo>⁢</mo>', '') # See notes below!
mml = ''.join(['<math xmlns="http://www.w3.org/1998/Math/MathML">', mml, '</math>'])
if filename is None:
tk = tkinter.Tk()
txt = tkinter.Text(tk)
txt.pack()
txt.insert(tkinter.END, mml)
tk.mainloop()
else:
with open(filename, 'w') as file:
file.write(mml)
which, depending on the second argument, either writes MathML to a file or displays it in a text box from which it can be copied and pasted. Having done that, give the command
Insert>OLE Object>Formula Object
and then, in the formula editor, either of
Tools>Import Formula…
Tools>Import MathML from Clipboard
Alternatively, and perhaps best of all, rather than using “Insert>OLE Object>Formula Object”, give the command
Insert>OLE Object>OLE Object…
choose “Create from file” and perhaps “Link to file” as well, then navigate to a file with suffix “.mml”.
There are a few interesting/confusing features which puzzled me along the way…
-
LibreOffice seems only to accept ‘presentation’ style MathML. If you give it ‘content’ style MathML (sympy’s default) it fails silently.
-
sympy’s mathml converter doesn’t add the surrounding <math>…</math> elements, and LibreOffice fails silently if these are missing.
-
If there are <mo>⁢</mo> elements in the MathML, LibreOffice Import fails silently (though, curiously, giving LibreOffice Math’s File>Open… command is happy to accept an MML file which contains such elements, as is “Insert>OLE Object>OLE Object…”).
This all tested with LibreOffice version 24.8.4.2 and sympy version 1.13.3