Java draw Superscript and Subscript Text in PDF

This article will show you how to use Spire.PDF for Java to draw superscript and subscript text to PDF file in Java applications.

Draw Superscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

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

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Superscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Super_Script);
        text = "Superscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/superScript.pdf";
        doc.saveToFile(result);
    }
}

Effective screenshot:

Java draw Superscript and Subscript Text in PDF

Draw Subscript Text

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

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

        //Create a new PdfDocument instance
        PdfDocument doc = new PdfDocument();
        //Add a page to pdf
        PdfPageBase page = doc.getPages().add();

        //Set the font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,14),true);
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));

        //Set initial (x, y) coordinate
        float x = 120f;
        float y = 100f;

        //Draw text string
        String text = "Sample Text";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y));

        //Measure the string
        Dimension2D size = font.measureString(text);
        x += size.getWidth();

        //Draw the text string and set the format as Subscript
        PdfStringFormat format = new PdfStringFormat();
        format.setSubSuperScript(PdfSubSuperScript.Sub_Script);
        text = "Subscrip";
        page.getCanvas().drawString(text, font, brush, new Point2D.Float(x, y), format);

        //Save the document to file
        String result="output/subScript.pdf";
        doc.saveToFile(result);
    }
}

Output:

Java draw Superscript and Subscript Text in PDF