Mar 12
|
When using non standard fonts in a PDF we need to embed the font so it is available to whoever is reading that PDF (as they probably will not have the font installed on their system).
iText provides a great library for generating PDF’s using Java. It also includes the ability to embed fonts.
If the font is not installed on your system and you instead have a font file that you want to embed then you need to first register the font with iText FontFactory.
Then get the font from the FontFactory making sure to tell it that you want the font embedded.
import java.io.FileOutputStream; import com.itextpdf.text.Document; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; public class EmbedFont { public static void main(String[] args) throws Exception { // Pass name of font file on command line String filename = args[1]; // Register the font FontFactory.register(filename, filename); // Get the font NB. last parameter indicates font needs to be embedded Font font = FontFactory.getFont(filename, BaseFont.CP1252, BaseFont.EMBEDDED); // Lets now use the font to create a PDF Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename+".pdf")); document.open(); Paragraph p = new Paragraph("This uses an embedded font", font); document.add(p); document.close(); } }