We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

MathML to PNG - nearly there!

With the new InsertHtml support for MathML in 16.4 it should be possible to use Aspose.Words to create a PNG file from MathML. I’m halfway there but need some help:

Firstly, I do this to get my mathML into a Word document:

var mathMl = @"<math xmlns=""http://www.w3.org/1998/Math/MathML"">123×<mi mathvariant=""normal"">π";
Document doc = new Document();
var builder = new DocumentBuilder(doc);

Great - works well, now the task is to extract that as an image. The post here:

private static void DocEquationToPng(Document doc, string targetFilename)
    // Based on code from https://forum.aspose.com/t/55152 DocumentBuilder builder = new DocumentBuilder(doc); 
    LayoutCollector collector = new LayoutCollector(doc);
    LayoutEnumerator enumerator = new LayoutEnumerator(doc);

    NodeCollection equations = doc.GetChildNodes(NodeType.OfficeMath, true);

    OfficeMath targetEq = (OfficeMath)equations\[0\];
    OfficeMath clonedEq = (OfficeMath)targetEq.Clone(true);

    // TODO: The following fails
    // enumerator.Current = collector.GetEntity(targetEq);
    // Instead here the parent node is used
    enumerator.Current = collector.GetEntity(targetEq.ParentNode);

    Shape container = new Shape(doc, ShapeType.TextBox);

    // TODO: how to set the TextBox size automatically?  Currently using:
    // container.Width = 1.5 * enumerator.Rectangle.Width;
    // container.Height = 1.5 * enumerator.Rectangle.Height;
    // is not effective therefore using fixed values for now.

    container.Width = 200;
    container.Height = 200;
    container.TextBox.FitShapeToText = true;  // Seems to automatically set width?

    Paragraph paragraph = new Paragraph(doc);



    container.GetShapeRenderer().Save(targetFilename, new ImageSaveOptions(SaveFormat.Png));

There are problems as marked with TODO. My questions are:
How can we get the correct size to set the text box?
How can we set the size of the output. Currently the equation output is too small.https://forum.aspose.com/t/55152

Hi Darren,

Thanks for your inquiry. Please use following code example to convert OfficeMath to Png. Hope this helps you.

var mathMl =@"<math xmlns=""http://www.w3.org/1998/Math/MathML""><mroot><mfrac><mn>1</mn><mn>2</mn></mfrac><mn>3</mn></mroot><mo>&#x000D7;</mo><mi mathvariant=""normal"">&#x003C0;</mi></math>";
Document doc = new Document();
var builder = new DocumentBuilder(doc);
OfficeMath math = (OfficeMath)doc.GetChild(NodeType.OfficeMath, 0, true);
ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png);
options.Resolution = 200;
math.GetMathRenderer().Save(MyDir + @"Out.png", options);

Great - thank you!

Hi Darren,

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.