Wednesday 21 September 2016

Itext: setTextRise: Specify superscript and subscripts

Chunk class provides setTextRise method to set the text displacement relative to the baseline. Positive values rise
the text, negative values lower the text.

public Chunk setTextRise(final float rise)

Following program displays country and their language code as superscript.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.PdfWriter;

public class HelloWorld {
 private static List<String> countries = Arrays.asList("India - Assamese", "India - Bengali", "India - English",
   "India - Gujarati", "India - Hindi", "India - Kannada", "India - Konkani", "India - Malayalam",
   "India - Marathi", "India - Oriya", "India - Punjabi", "India - Sanskrit", "India - Tamil",
   "India - Telugu");

 private static List<String> countryCodes = Arrays.asList("as-IN", "bn-IN", "en-IN", "gu-IN", "hi-IN", "kn-IN",
   "kok-IN", "ml-IN", "mr-IN", "or-IN", "pa-IN", "sa-IN", "ta-IN", "te-IN");

 private static Font font = FontFactory.getFont(FontFactory.COURIER, 20, Font.NORMAL, BaseColor.BLACK);
 private static Font superScriptFont = FontFactory.getFont(FontFactory.COURIER, 10, Font.ITALIC, BaseColor.BLACK);
 private static Font fontHeading = FontFactory.getFont(FontFactory.HELVETICA, 25, Font.BOLD,
   new BaseColor(255, 0, 0));

 public static void main(String args[]) throws FileNotFoundException, DocumentException {
  Document document = new Document();

  PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("countries.pdf"));
  writer.setInitialLeading(16);

  document.open();

  document.add(new Chunk("Langauage codes in India", fontHeading));
  document.add(Chunk.NEWLINE);
  document.add(Chunk.NEWLINE);

  int counter = 0;
  for (String country : countries) {

   Chunk chunk = new Chunk(country, font);
   document.add(chunk);

   String code = "(" + countryCodes.get(counter) + ")";
   counter++;
   Chunk superScript = new Chunk(code, superScriptFont);
   superScript.setTextRise(6);
   document.add(superScript);

   document.add(Chunk.NEWLINE);
   document.add(Chunk.NEWLINE);
  }

  document.close();

 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment