Tutorials     About     RSS
Tech and Media Labs

Java IText: Font

Jakob Jenkov
Last update: 2014-05-24

You can specify fonts for most text objects (Chunk, Phrase, Paragraph etc.) in IText. Actually, you can do a lot with fonts in IText. Too much to cover here, so I'll just cover the basics. Get the book "IText in Action" to get the full story on fonts.

To use a font you must first create the font. Then you pass it to the text object in it's constructor. Here is a simple code example:

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

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

public class FontExample {

  public static void main(String[] args) {

    Document document = new Document();

    try {
      PdfWriter.getInstance(document,
        new FileOutputStream("Font.pdf"));
      
          Font font1 = new Font(Font.FontFamily.HELVETICA  , 25, Font.BOLD);
          Font font2 = new Font(Font.FontFamily.COURIER    , 18,
          Font.ITALIC | Font.UNDERLINE);
          Font font3 = new Font(Font.FontFamily.TIMES_ROMAN, 27);
      
      document.open();

      document.add(new Chunk(    "This is sentence 1. ", font1));
      document.add(new Phrase(   "This is sentence 2. ", font2));
      document.add(new Paragraph("This is sentence 3. ", font3));

      document.close();

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

  }
}

Here is what the generated document looks like:

An IText Font example
An IText Font example

Jakob Jenkov

Featured Videos





















Sponsored Ads

Maildroppa - Smart Email Marketing Solution
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next