Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextPdf7 - Get font from resources

I am using iText7 to create PDF's with Java. I use some custom fonts, and those files are on the resources folder.

While I am testing and running the app on netbeans, this works perfectly:

PdfFontFactory.register("./src/main/resources/GOTHAM-BOLD.otf", "gotham-bold");
PdfFont gBold = PdfFontFactory.createRegisteredFont("gotham-bold", PdfEncodings.IDENTITY_H);

But when I build, and try running the app and generating the PDF file, iText can't find the font files, because it needs the direct path to it. What alternatives do I have? I really need to this in order to work in any pc (like the other resources).

like image 489
zediogoviana Avatar asked Oct 29 '25 08:10

zediogoviana


1 Answers

I am not quite sure why you are using aliases. You can use other factory methods that accept byte[] arrays in combination with Class.getResourceAsStream(String) to retrieve the contents of the font resource which can be used to create a FontProgram instance and then construct a PdfFont.

You code can be changed as follows:

// Apache Commons IO is used, but any way of retrieving bytes from stream will suffice
byte[] fontContents = IOUtils.toByteArray(getClass().getResourceAsStream("GOTHAM-BOLD.otf"));

FontProgram fontProgram = FontProgramFactory.createFont(fontContents);
document.setFont(PdfFontFactory.createFont(fontProgram, PdfEncodings.IDENTITY_H));

If you work in a static context, you can use it like Main.class.getResourceAsStream() (put your class name instead of Main).

Make sure the font resource appears in the final assembly and you are good to go. There is no dependency on any URLs in this approach.

like image 141
Alexey Subach Avatar answered Oct 31 '25 13:10

Alexey Subach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!