Insert MathML as plain text for Word 2010 to render it as an equation
See original GitHub issueHi everybody,
I am trying to insert some MathML code into a *.docx document. To do so, I do the following:
#!/bin/env python
# -*- coding: utf8 -*-
from docx import Document
doc = Document('template.docx')
# Word needs a specific XML namespace in the '<math>' tag in order to embed MathML text into a math area
# Also, the MathML expression must contain no newline or Word will create one distinct math area for each line
math_ml = '<math xmlns="http://www.w3.org/1998/Math/MathML"><mfrac><mn>1</mn><mn>2</mn></mfrac></math>'
# Insert the MathML text into Word
doc.add_paragraph().add_run(text=math_ml, style=None).font.math = True
doc.save('test.docx')
When I open the resulting document in Word 2010, this is what I see. The math area has been correctly created, but the code itself has not been rendered.
The interesting thing is when I open the resulting document and then copy then paste the MathML code from/to the math area using “Paste as plain text” directly from Word UI, it gets properly rendered.
I have come to the conclusion that when a style is applied to the MathML text, then Word does not render it as an equation. And this assertion is verified by the fact that when you use another paste option like “Keep source formatting” or “Melt both formats”, then the equation is not rendered using Word UI.
My question is: how can I insert the MathML text as plain text into Word without any style using python-docx lib ? I tried those, but none of them worked:
doc.add_paragraph().add_run(text=math_ml, style=None).font.math = True
doc.add_paragraph().add_run(text=math_ml, style='').font.math = True
doc.add_paragraph().add_run(text=math_ml).font.math = True
Or maybe this is currently not supported by this library ?
Thanks for your help 😃
Issue Analytics
- State:
- Created 7 years ago
- Reactions:5
- Comments:18 (1 by maintainers)
I solved this issue with the latex2mathml module. Please buy coffee for the man who wrote it
Hi @scizers ,
I’ve managed to make it work. However, you must use the MathML to Office MathML stylesheet in order to transform the MathML data into Office-compatible MathML.
The stylesheet is installed along with Microsoft Office and you can find it in:
C:\Program Files (x86)\Microsoft Office\Office14\MML2OMML.XSL
.You may also need to remove any namespace from the
<math>
tag before transforming it into Office MathML. Let me know if it works for you too.