2012-06-12 97 views
3

我使用MathML創建一些數據塊,我需要將它通過OpenXML SDK插入到docx文件中。我聽說有可能,但我沒有管理它。有人能幫我解決這個問題嗎?OpenXML SDK和MathML

回答

7

據我所知,OpenXml SDK不支持演示MathML開箱即用。

相反,OpenXml SDK支持Office MathML。 因此,要將演示文稿MathML插入Word文檔,我們首先需要 將演示文稿MathML轉換爲Office MathML。

幸運的是,微軟提供了一個XSL文件(稱爲MML2OMML.xsl)來演示MATHML 改造成辦公樓MathML了。文件MML2OMML.xsl位於%ProgramFiles%\Microsoft Office\Office12下。 結合.Net框架類 XslCompiledTransform我們可以將演示文稿MathML轉換爲Office MathML。

下一步是從轉換的MathML創建一個OfficeMath對象。 OfficeMath類表示一個包含WordprocessingML的運行,該運行應像處理Office Open XML Math一樣進行處理。 欲瞭解更多信息,請參閱MSDN

演示文稿MathML不包含字體信息。爲了得到一個很好的結果 我們必須添加字體信息到創建的OfficeMath對象。

在最後一步,我們必須將OfficeMath對象添加到我們的word文檔中。 在下面的示例中,我只需在名爲template.docx的 word文檔中搜索第一個Paragraph,並將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); 
    } 
    } 
} 
+0

非常感謝您的回答!我非常感謝它!我已經試過你的代碼,並且我已經成功了!你救了我!再次感謝! – user1450792

+0

@ user1450792:不客氣!請點擊答案旁邊的複選標記,接受我的答案,將其從空心切換爲綠色。 – Hans

+0

非常好的解決方案@Hans。但我怎麼能做到相反。我想用OMML將word文件的xml內容轉換爲包含MML的純文本..!? – serene