Tech and Media Labs
This site uses cookies to improve the user experience.




Java IText: Superscript + Subscript

Jakob Jenkov
Last update: 2014-05-24

You can write text as superscript or subscript using the Chunk class, and it's setTextRise() method. You use a positive text rise value for superscript, and a negative text rise value for subscript.

Here is a simple code example:

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

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

    Document document = new Document();

    try {
      PdfWriter.getInstance(document,
            new FileOutputStream("SuperSubScript.pdf"));

      document.open();

      Chunk normalText =
            new Chunk("Normal text at normal y-location. ");
      document.add(normalText);

      Chunk superScript = new Chunk("Superscript");
      superScript.setTextRise(5f);
      document.add(superScript);

      Chunk moreNormalText =
            new Chunk(". More normal y-location text. ");
      document.add(moreNormalText);

      Chunk subScript = new Chunk("Subscript");
      subScript.setTextRise(-5f);
      document.add(subScript);

      document.close();

    } catch (DocumentException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

  }

}

Here is what the generated document looks like:

IText Chunk's with superscript and subscript
IText Chunk's with superscript and subscript

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC