我使用Apache POI將文本與乳膠風格方程轉換爲MS word文檔。在一些幫助下,我能夠成功實現它,但是如果該行有多個等式,那麼它會產生不正確的結果。如何使用Apache POI Word中的文本添加內嵌多個方程式?
下面是我的代碼:
import java.io.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMathPara;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import uk.ac.ed.ph.snuggletex.SnuggleInput;
import uk.ac.ed.ph.snuggletex.SnuggleEngine;
import uk.ac.ed.ph.snuggletex.SnuggleSession;
import java.io.IOException;
public class CreateWordFormulaFromMathML {
static File stylesheet = new File("MML2OMML.XSL");
static TransformerFactory tFactory = TransformerFactory.newInstance();
static StreamSource stylesource = new StreamSource(stylesheet);
static CTOMath getOMML(String mathML) throws Exception {
Transformer transformer = tFactory.newTransformer(stylesource);
StringReader stringreader = new StringReader(mathML);
StreamSource source = new StreamSource(stringreader);
StringWriter stringwriter = new StringWriter();
StreamResult result = new StreamResult(stringwriter);
transformer.transform(source, result);
String ooML = stringwriter.toString();
stringwriter.close();
CTOMath ctOMath = CTOMath.Factory.parse(ooML);
return ctOMath.getOMathArray(0);
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
String mstr = "The expression is as: $ax^2 + bx = c$ is easier to understand than $$ax^2 + \\frac{\\sin^{-1}\\theta}{\\cot{-1}} \\times y_1$$ or anything in \\[ ay^2 + b_2 \\theta\\]";
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
// run.setText("");
SnuggleEngine engine = new SnuggleEngine();
SnuggleSession session = engine.createSession();
SnuggleInput input = new SnuggleInput(mstr);
session.parseInput(input);
String mathML = session.buildXMLString();
System.out.println("Input " + input.getString() + " was converted to:\n" + mathML + "\n\n");
for(String s : mathML.split("\\s+(?=<math)|(?<=</math>)\\s+")){
if (s.startsWith("<math"))
{
CTOMath ctOMath = getOMML(s);
System.out.println(s);
CTP ctp = paragraph.getCTP();
ctp.setOMathArray(new CTOMath[]{ctOMath});
}
else
{
run.setText(s + " ");
System.out.println(s);
}
}
document.write(new FileOutputStream("CreateWordFormulaFromMathML.docx"));
document.close();
}
}
這種生產與
表達的文件是:比較容易理解比或在y^2 + B_2 \ THETA
注意什麼:(ay^2 + b_2 \ theta)在字方程格式中是正確的。
我需要的是內聯多行方程的文本。
它工作得很好!謝謝! –