Adding SmallCap style in PDF with Itext API

Itext API does not support smallcaps styling by default. So if we want to get this style in pdf, then we should use the AlegreyaSansSC-Light.ttf from Google fonts

The link is https://www.google.com/fonts/specimen/Alegreya+Sans+SC

Please refer the below code on how to use this new font in the code


import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

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

public class PDFMain {

    public static void main(String[] args) throws DocumentException, FileNotFoundException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream("/home/bala/itext.pdf"));
        document.open();
        document.addAuthor("Balachandar");
        Paragraph paragraph1 = new Paragraph();
        paragraph1.add(new Chunk("Test with Open sans font"));
        paragraph1.setFont(AppFontFactory.getOpenSansFont());
        Paragraph paragraph2 = new Paragraph();
        paragraph2.add(new Chunk("Test with Normal sans font"));
        Paragraph paragraph3 = new Paragraph();
        Chunk chunk = new Chunk("test small");
        chunk.setFont(AppFontFactory.getSmallCapsPdfFont());
        paragraph3.add(chunk);
        document.add(paragraph1);
        document.add(paragraph2);
        document.add(paragraph3);
        document.close();
    }

    public static class AppFontFactory {

        //Assume that the "customfonts" is folder which contains all the fonts you want to use it
        static {
            FontFactory.register("customfonts/OpenSans-Regular.ttf", "opensans");
            FontFactory.register("customfonts/AlegreyaSansSC-Light.ttf", "alegreyasans");
        }
        public static Font getSmallCapsPdfFont() {
            return FontFactory.getFont("alegreyasans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        }
        public static Font getOpenSansFont() {
            return FontFactory.getFont("opensans", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);
        }
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s