Frank Endriss
Frank Endriss

Reputation: 140

How to programmatically load font extension at runtime?

I know about the jasperreports_extension.properties and how to put in into classpath to make fonts available to jasper reports.

I want to load them fonts dynamically while runtime, without them being available on the classpath at application startup.

Is there a API in Jasper I can use, and if yes, how? If possible, I would prefer an answer for Jasper 5.x.

Upvotes: 1

Views: 2878

Answers (1)

dada67
dada67

Reputation: 5103

You can programmatically register font extensions and other extension types by creating a JasperReportsContext instance (such as SimpleJasperReportsContext), adding the extensions to the context object and then using it when filling and exporting reports.

The code would look something like this:

//create the context object and the font extension
SimpleJasperReportsContext jasperReportsContext = new SimpleJasperReportsContext();

SimpleFontFamily fontFamily = new SimpleFontFamily(jasperReportsContext);
fontFamily.setName("family name");//to be used in reports as fontName
fontFamily.setPdfEmbedded(true);
fontFamily.setPdfEncoding("Identity-H");

SimpleFontFace regular = new SimpleFontFace(jasperReportsContext);
regular.setTtf("font ttf path");
fontFamily.setNormalFace(regular);

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);
...
JasperExportManager.getInstance(jasperReportsContext).exportToPdf(jasperPrint);
...
JRPdfExporter exporter = new JRPdfExporter(jasperReportsContext);

Upvotes: 4

Related Questions