Java IText:上标+下标

时间:2020-01-09 10:36:10  来源:igfitidea点击:

我们可以使用Chunk类和setTextRise()方法将文本写为上标或者下标。我们对上标使用正文本上升值,对下标使用负文本上升值。

这是一个简单的代码示例:

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();
    }

  }

}