Monday, March 23, 2015

How to initialize Font object from ttf file - Itext

P
Itext is a strong library for you to process PDF document in Java, C#. It allows you to do everything with your own PDF file such as create, design, encrypt or place a digital signature...
In this short article, I will show to how to load an external font file (ttf) into Font object of itext library.
PDF just is a kind of document likes Word, you can present various font styles. Assume that you have a font file (abc.ttf) this font is not typical and you want to use it for your PDF. This sample will help you out.

Load ttf file into com.itextpdf.text.Font

package com.it4shared.fontitext;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;


public class FontItext {

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  FontFactory.register("/opt/times.ttf");
  Font textFont = FontFactory.getFont("Times New Roman", BaseFont.IDENTITY_H, 
  BaseFont.EMBEDDED, 10);
 }

}
To know the font name, Just double click to open the font file, the Font Viewer will show you what font name is.
Make it more colorful

By adding this line. Your font will be RED. More colors can be found here.

textFont.setColor(BaseColor.RED);

No comments:

Post a Comment