How can I add embedded equations to docx files by using Apache POI?

我怕爱的太早我们不能终老 提交于 2019-12-01 14:05:21

This is not really complicated:

import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTRad;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;
import org.openxmlformats.schemas.officeDocument.x2006.math.STStyle;
/*
To
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMath;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTRad;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;
import org.openxmlformats.schemas.officeDocument.x2006.math.STStyle;
the fully ooxml-schemas-1.3.jar is needed as mentioned in https://poi.apache.org/faq.html#faq-N10025
*/

public class CreateWordFormula {

 public static void main(String[] args) throws Exception {

  XWPFDocument doc= new XWPFDocument();

  XWPFParagraph paragraph = doc.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("The Formula: ");

  CTOMath cTOMath = paragraph.getCTP().addNewOMath();
  CTR cTR = cTOMath.addNewR();
  cTR.addNewRPr().addNewSty().setVal(STStyle.P);
  cTR.addNewT2().setStringValue("a²+b²=c²");

  run=paragraph.createRun();  
  run.setText(" text after the formula");

  paragraph = doc.createParagraph();
  run=paragraph.createRun();  
  run.setText("The Formula: ");

  cTOMath = paragraph.getCTP().addNewOMath();
  CTRad cTRad = cTOMath.addNewRad();
  cTR = cTRad.addNewDeg().addNewR();
  cTR.addNewRPr().addNewSty().setVal(STStyle.P);
  cTR.addNewT2().setStringValue("2");
  cTR = cTRad.addNewE().addNewR();
  cTR.addNewRPr().addNewSty().setVal(STStyle.P);
  cTR.addNewT2().setStringValue("a²+b²");

  run=paragraph.createRun();  
  run.setText(" text after the formula");  

  doc.write(new FileOutputStream("WordFormula.docx"));

 }
}

For CTOMath see http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/officeDocument/x2006/math/CTOMath.java#CTOMath.addNewRad%28%29.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!