Search code examples
javafontsitextitextpdf

Loading Fonts from Jar while writing PDF-A (archive) file


I am using PdfAWriter to create PDF-A (PDF Archive format) file and using .ttf to embed fonts in PDF. My TTF files are under config folder . And when I try to create font like below it works in local

Font BOLD_10 = FontFactory.getFont("./config/FreeSansBold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

Document document; //Document created using PDF-A writer

PdfPTable table = new PdfPTable(new float[] { 50,50 });
table.setWidthPercentage(new Float(100));

Paragraph paragraph = new Paragraph("Header 1", BOLD_10);
document.add(paragraph);

If I try to build a jar file and place the .tff inside the jar, below code doesnt work, since it wont be able to find the path of ttf file:

Font BOLD_10 = FontFactory.getFont("./config/FreeSansBold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);

How can I configure my font file path to pick dynamically from jar?

We have tried using built-in fonts and BaseFont instead of .ttf, but they don't work (throw exception at run time) for "PDF-A" file.

Apart from using TTF, is there any alternative to embed fonts in a PDF-A file?


Solution

  • Solved the problem like this - (1) Placed the .ttf files under "com/mycompany/pdfutility/fonts" directory and included them in the jar file. (2) Referred to this file in the code like this:

    Font BOLD_10 = FontFactory.getFont("/com/mycompany/pdfutility/fonts/FreeSansBold.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 10);