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?
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);
If you use iText 7, you can try this:
First put your font.ttf
file in resources dir such as fonts/simsun.ttf
Then,
byte[] fontByte = IOUtils.toByteArray(Main.class.getResource("/fonts/simsun.ttf").openStream());
PdfFont font = PdfFontFactory.createFont(fontByte, PdfEncodings.IDENTITY_H);
IOUtils is from commons-io
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.