package cn.flightfeather.supervision.docx4j.simpleDemo; import org.docx4j.Docx4J; import org.docx4j.TraversalUtil; import org.docx4j.XmlUtils; import org.docx4j.finders.ClassFinder; import org.docx4j.jaxb.Context; import org.docx4j.math.CTOMathPara; import org.docx4j.openpackaging.packages.WordprocessingMLPackage; import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart; import org.docx4j.wml.P; import javax.xml.bind.JAXBElement; /** * Basic demo handling Office Math. * */ public class MathsEquationsFormulae { public static void main(String[] args) throws Exception { // First, create/save a docx containing a formula. WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage(); MainDocumentPart mdp = wordMLPackage.getMainDocumentPart(); P p = new P(); mdp.getContent().add(p); JAXBElement omathpara = (JAXBElement) XmlUtils.unmarshalString(openXML); // or could have used generated code which uses JAXB factory approach p.getContent().add(omathpara); String filename = System.getProperty("user.dir") + "/OUT_maths.docx"; Docx4J.save(wordMLPackage, new java.io.File(filename), Docx4J.FLAG_SAVE_ZIP_FILE); System.out.println("Saved " + filename); // The above shows how to unmarshall it // Now, show how to marshall existing maths content // first, find it ClassFinder finder = new ClassFinder(CTOMathPara.class); new TraversalUtil(mdp.getContent(), finder); // Get the first result Object o = finder.results.get(0); System.out.println(o.getClass().getName()); // Can't use XmlUtils.marshaltoString(o) because // CTOMathPara is missing an @XmlRootElement annotation, // so be explicit String result = XmlUtils.marshaltoString( o, true, true, Context.jc, "http://schemas.openxmlformats.org/officeDocument/2006/math", "oMathPara", CTOMathPara.class); System.out.println(result); } // generated using docx4j code gen at http://webapp.docx4java.org/OnlineDemo/PartsList.html or the Word AddIn private static String openXML = "" + "" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" +"" + "x+a" +"" +"" +"" +"" + "" + "" + "" + "" +"" + "n" +"" +"" +"" + "" + "" + "" +"" + "=" +"" + "" + "" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" +"" + "k=0" +"" +"" + "" + "" + "" + "" +"" + "n" +"" +"" + "" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" +"" + "n" +"" +"" + "" + "" + "" + "" +"" + "k" +"" +"" +"" +"" +"" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" +"" + "x" +"" +"" + "" + "" + "" + "" +"" + "k" +"" +"" +"" + "" + "" + "" + "" + "" +"" +"" +"" + "" + "" + "" + "" +"" + "a" +"" +"" + "" + "" + "" + "" +"" + "n-k" +"" +"" +"" +"" +"" +"" +""; }