How to set a new font at runtime


Hello everyone,

I've been strugling with a pdf i have to generate in greek. As you may immagine not every font has greek letters so I had to embbed my own in the project and this is where my issu began.

I'm developing for an OSGI environment so I tried to add my generated jar from jasperSoft studio into the application classpath, once I've wasted many hours trying to make it work I found this post on stack overflow:

The important part is that we could create a Jasper context of our own and add the font there:

SimpleJasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();
SimpleFontFamily fontFamily = new SimpleFontFamily(jasperReportsContext);
fontFamily.setName("family name");//to be used in reports as fontName
SimpleFontFace regular = new SimpleFontFace(jasperReportsContext);
regular.setTtf("font ttf path");
jasperReportsContext.setExtensions(FontFamily.class, Arrays.asList(fontFamily));
//use the context when filling and exporting reports
//note that there are variations here depending on the API you use for filling and exporting
JasperPrint jasperPrint = JasperFillManager.getInstance(jasperReportsContext).fill(jasperReport, params);

This seemed a good path to follow but now i'm not entirely sure it's possible to add a font in runtime. Inside the jasperReports I've found the method used to fill the report:

     * @see #fill(InputStream, Map, JRDataSource)
    public static JasperPrint fillReport(
        InputStream inputStream, 
        Map<String,Object> parameters,
        JRDataSource dataSource
        ) throws JRException
        return getDefaultInstance().fill(inputStream, parameters, dataSource);

Which means that it will alway ignore my custom instance with my jasperReportContext and will create a new one with it's default context.

Having said all that, I would like to know if there is any wsay to achive my goal of registering a font (ttf) programatically / in run time

Best Regards

raphaeltmolnar's picture
Joined: Aug 19 2020 - 4:25am
Last seen: 1 month 4 weeks ago

0 Answers:

No answers yet