DEV Community

CodeSharing
CodeSharing

Posted on

Insert Superscripts and Subscripts in Word using Java

Superscript and subscript are characters that appear slightly above or below your regular text and are often used in mathematical as well as chemical formulas. This article will demonstrate how to insert superscripts and subscripts in a Word document using a 3rd party free API.

Installation (2 Methods)
● Download the free API (Free Spire.Doc for Java) and unzip it. Then add the Spire.Doc.jar file to your Java application as dependency.

● You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
   <repository>
      <id>com.e-iceblue</id>
      <name>e-iceblue</name>
      <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
   </repository>
</repositories>
<dependencies>
   <dependency>
      <groupId>e-iceblue</groupId>
      <artifactId>spire.doc.free</artifactId>
      <version>3.9.0</version>
   </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Relevant Code Snippet

import com.spire.doc.*;
import com.spire.doc.documents.BreakType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;

public class SubSuperScritp {
    public static void main(String[] args) {

        //Create a Document instance
        Document doc = new Document();
        //Add a section
        Section sec = doc.addSection();

        //Add a paragraph
        Paragraph para = sec.addParagraph();

        //Insert text and set some of the characters as superscript
        para.appendText("A");
        para.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        para.appendText("+B");
        para.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
        para.appendText("=C");
        para.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);

        //Add a line break
        para.appendBreak(BreakType.Line_Break);

       //Insert text and set some of the characters as subscript
        para.appendText("H");
        para.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
        para.appendText("O");

        //Save the document
        doc.saveToFile("InsertSubSuperScript.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

Top comments (0)