2015-09-24 83 views
0

我需要在odt文檔中添加數學公式。我還沒有找到如何去做的例子。我試了下面的代碼。但它會生成一個空的公式。我不知道如何添加它像c = a + b。有人解決了類似的問題?公式應該由MathML代碼編寫。但我不知道在哪裏插入它。如何使用odfpy在odt文檔中添加數學公式?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import odf 
import odf.opendocument 
import odf.math 
import odf.text 

def main(): 
    doc = odf.opendocument.OpenDocumentText() 
    p = odf.text.P(text=u'text') 
    df = odf.draw.Frame(zindex=0, anchortype='as-char') 
    p.addElement(df) 
    doc.text.addElement(p) 

    math = odf.math.Math() 
    do = odf.draw.Object() 
    do.addElement(math) 
    df.addElement(do) 

    outputfile = u'result' 
    doc.save(outputfile, True) 
if __name__ == '__main__': 
    main() 

回答

0
#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import odf 
from odf.opendocument import OpenDocumentText 
from odf.element import Element 
from odf.text import P 
from odf.math import Math 
from namespaces import MATHNS 


def main(): 
    doc = OpenDocumentText() 
    p = P(text=u'text') 
    df = odf.draw.Frame(zindex=0, anchortype='as-char') 
    p.addElement(df) 
    doc.text.addElement(p) 

    formula =u'c=sqrt(a^2+b^2)' 
    math = Math() 
    annot = Element(qname = (MATHNS,u'annotation')) 
    annot.addText(formula, check_grammar=False) 
    annot.setAttribute((MATHNS,'encoding'), 'StarMath 5.0', check_grammar=False) 
    math.addElement(annot) 
    do = odf.draw.Object() 
    do.addElement(math) 
    df.addElement(do) 

    outputfile = u'result' 
    doc.save(outputfile, True) 

if __name__ == '__main__': 
    main()