How to use Google Fonts in Itext API

For one of my recent project, there is an export to PDF functionality. So the application should generate the pdf on the fly and render it on the browser when the user clicks on export link. We use Itext API to generate the PDF

As we use lower version of the Itext API, We don’t have much support for the new fonts. But Itext provides a way to add the new fonts with the help of FontFactory class.

We can get open source fonts from Google[https://www.google.com/fonts/] and use it in our code. Sample code is given below


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"));
        document.add(paragraph1);
        document.add(paragraph2);
        document.close();
    }

    public static class AppFontFactory {

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

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