OpenXML SDK和MathML

use*_*792 3 equation mathml docx openxml

我使用MathML创建一些数据块,我需要将它通过OpenXML SDK插入到docx文件中.我听说有可能,但我没有管理它.有人可以帮我解决这个问题吗?

Han*_*ans 9

据我所知,OpenXml SDK不支持开箱即用的演示MathML.

相反,OpenXml SDK支持Office MathML.因此,要将演示MathML插入到word文档中,我们首先必须将演示MathML转换为Office MathML.

幸运的是,Microsoft提供了一个XSL文件(称为MML2OMML.xsl)来将表示MathML转换为Office MathML.文件MML2OMML.xsl位于%ProgramFiles%\Microsoft Office\Office12.结合.Net Framework类, XslCompiledTransform我们可以将表示MathML转换为Office MathML.

下一步是OfficeMath从转换后的MathML 创建一个对象.本OfficeMath类表示包含WordprocessingML中,就好像它是的Office Open XML数学这应处理的运行.有关详细信息,请参阅MSDN.

演示文稿MathML不包含字体信息.为了获得良好的结果,我们必须将字体信息添加到创建的OfficeMath对象.

在最后一步中,我们必须将OfficeMath对象添加到word文档中.在下面的示例中,我只是Paragraph在名为template.docx的word文档中搜索第一个,并将该OfficeMath对象添加到找到的段落中.

XslCompiledTransform xslTransform = new XslCompiledTransform();

// The MML2OMML.xsl file is located under 
// %ProgramFiles%\Microsoft Office\Office12\
xslTransform.Load("MML2OMML.xsl");

// Load the file containing your MathML presentation markup.
using (XmlReader reader = XmlReader.Create(File.Open("mathML.xml", FileMode.Open)))
{
  using (MemoryStream ms = new MemoryStream())
  {
    XmlWriterSettings settings = xslTransform.OutputSettings.Clone();

    // Configure xml writer to omit xml declaration.
    settings.ConformanceLevel = ConformanceLevel.Fragment;
    settings.OmitXmlDeclaration = true;

    XmlWriter xw = XmlWriter.Create(ms, settings);

    // Transform our MathML to OfficeMathML
    xslTransform.Transform(reader, xw);
    ms.Seek(0, SeekOrigin.Begin);

    StreamReader sr = new StreamReader(ms, Encoding.UTF8);

    string officeML = sr.ReadToEnd();

    Console.Out.WriteLine(officeML);

    // Create a OfficeMath instance from the
    // OfficeMathML xml.
    DocumentFormat.OpenXml.Math.OfficeMath om =
      new DocumentFormat.OpenXml.Math.OfficeMath(officeML);

    // Add the OfficeMath instance to our 
    // word template.
    using (WordprocessingDocument wordDoc =
      WordprocessingDocument.Open("template.docx", true))
    {
      DocumentFormat.OpenXml.Wordprocessing.Paragraph par =
        wordDoc.MainDocumentPart.Document.Body.Descendants<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().FirstOrDefault();        

      foreach (var currentRun in om.Descendants<DocumentFormat.OpenXml.Math.Run>())
      {
        // Add font information to every run.
        DocumentFormat.OpenXml.Wordprocessing.RunProperties runProperties2 =
          new DocumentFormat.OpenXml.Wordprocessing.RunProperties();

        RunFonts runFonts2 = new RunFonts() { Ascii = "Cambria Math", HighAnsi = "Cambria Math" };        
        runProperties2.Append(runFonts2);

        currentRun.InsertAt(runProperties2, 0);
      }

      par.Append(om);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)