I am trying to add superscript and subscripts using apache poi in word file but not getting in same like below
getting like this but i need proper like this [1]: https://i.sstatic.net/ZhWyX.png
The only possibility to have something like this in a Word document is inserting an equation of form ex.
In Word GUI one would select Insert > Equation > ex.
Using Apache POI this can be done using following code:
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.CTSSubSup;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTOMathArg;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTR;
import org.openxmlformats.schemas.officeDocument.x2006.math.CTText;
public class CreateWordFormulaSubSup {
static CTOMath createOMathSupSub(String eText, String supText, String subText) {
CTOMath ctOMath = CTOMath.Factory.newInstance();
CTSSubSup ctSSubSup = ctOMath.addNewSSubSup();
CTOMathArg ctOMathArg = ctSSubSup.addNewE();
CTR ctR = ctOMathArg.addNewR();
CTText ctText = ctR.addNewT2();
ctText.setStringValue(eText);
ctOMathArg = ctSSubSup.addNewSup();
ctR = ctOMathArg.addNewR();
ctText = ctR.addNewT2();
ctText.setStringValue(supText);
ctOMathArg = ctSSubSup.addNewSub();
ctR = ctOMathArg.addNewR();
ctText = ctR.addNewT2();
ctText.setStringValue(subText);
return ctOMath;
}
static void createOMathInParagraph(XWPFParagraph paragraph, CTOMath ctOMath) {
CTOMath ctOMathTemp = paragraph.getCTP().addNewOMath();
paragraph.getCTP().setOMathArray(paragraph.getCTP().getOMathArray().length-1, ctOMath);
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Formula: ");
createOMathInParagraph(paragraph, createOMathSupSub("2000", "+2000", "-180"));
run = paragraph.createRun();
run.setText(" text after formula.");
paragraph = document.createParagraph();
FileOutputStream out = new FileOutputStream("./CreateWordFormulaSubSup.docx");
document.write(out);
out.close();
document.close();
}
}
Result: