Dependancy Setup
Add the library to your Java project via Maven. Include the repository and dependency in your pom.xml:
<repositories>
<repository>
<id>com.e-iceblue</id>
<url>http://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>2.7.3</version>
</dependency>
</dependencies>
For manual installasion, extract the downloaded package and include Spire.Doc.jar from the lib folder in your classpath.
Implementation Example
The SubSuperScript enumeration offers two constants: Super_Script and Sub_Script. Appending text and then accessing its CharacterFormat allows you to toggle thece styles on specific runs within a paragraph.
import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.documents.SubSuperScript;
public class ScriptStyler {
public static void main(String[] args) {
// Instantiate a new document and add a section
Document document = new Document();
Section section = document.addSection();
// Superscript usage
Paragraph supParagraph = section.addParagraph();
supParagraph.appendText("A");
supParagraph.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
supParagraph.appendText(" + B");
supParagraph.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
supParagraph.appendText(" = C");
supParagraph.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Super_Script);
// Subscript example: mathematical series
Paragraph subSeries = section.addParagraph();
subSeries.appendText("An = S");
subSeries.appendText("n").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
subSeries.appendText(" - S");
subSeries.appendText("n-1").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
// Subscript example: chemical formula
Paragraph subChemical = section.addParagraph();
subChemical.appendText("C");
subChemical.appendText("O");
subChemical.appendText("2").getCharacterFormat().setSubSuperScript(SubSuperScript.Sub_Script);
// Output file
document.saveToFile("FormattedScripts.docx", FileFormat.Docx_2013);
document.dispose();
}
}
After execution, the generated document displays correct superscripts in the first paragraph and subscripts in the following two, producing expressions like A² + B² = C², An = Sₙ - Sₙ₋₁, and CO₂.