How to load custom font in FontFactory.register in iText

14,832

Solution 1

You can get the path of the 'font' which are present in the resources folder, using contextClassLoader and can be used in the FontFactory file path.

URL font_path = Thread.currentThread().getContextClassLoader().getResource("fontname");
FontFactory.register(font_path.toString(), "test_font");

I have tested this code and it works fine.

Solution 2

The code was done by:

 FontFactory.register(System.getProperty("file.separator")+"resources"+System.getProperty("file.separator")+"fonts"+System.getProperty("file.separator")+"arial.‌​ttf", "my_bold_font");
 Font myBoldFont = FontFactory.getFont("my_bold_font");
Share:
14,832
99maas
Author by

99maas

Updated on June 04, 2022

Comments

  • 99maas
    99maas about 2 years

    I need your help in adding a custom font "arial.ttf" which is stored under the resources folder in my project in the FontFactory.register method in iText.

    The font path is as follows in the project from Windows Explorer:

    public_html\resources\fonts\arial.ttf

    The code for referring to the font is:

    FontFactory.register("/resources/fonts/arial.ttf", "my_bold_font");
    Font myBoldFont = FontFactory.getFont("my_bold_font");
    

    However when I ran the Java method, it always gives me the error:

    java.io.IOException: /resources/fonts/arial.ttf not found as file or resource.

    I tried with different paths for example:

    /public_html/resources/fonts/arial.ttf

    ../resources/fonts/arial.ttf

    /fonts/arial.ttf

    /arial.ttf

    But the result is the same that the file can't be found. So how to refer to the file?