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

天大地大妈咪最大 提交于 2020-01-11 07:47:55

问题


I want to create a docx file programatically via Apache POI.

I want to add some mathematical equations in some lines.

How can I do this in a way that when the user open the docx file it see that equations as docx equation form.

I mean I don't want simply give a background colour to that run, I want when the user does double click on my equation MS-Word open it in equation forms.

Thanks in advance


回答1:


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.



来源:https://stackoverflow.com/questions/35418453/how-can-i-add-embedded-equations-to-docx-files-by-using-apache-poi

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