Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change font name dynamically?

I am using Jasper jar to generate report on my J2EE project. I am able to generate the PDFs successfully without any issues. However I want the font name to be dynamically changed for all my PDFs based on settings which we configure on one place.

I came to know Conditional style which is useful to accomplish this. However I do have hundreds of fonts which cannot be conditionally styled on each and every place. This will make the report more worst.

I am looking for a suitable solution which helps me to change the fonts on jasper PDFs dynamically.

like image 488
Srinath Mahe Avatar asked Oct 20 '17 11:10

Srinath Mahe


1 Answers

The simplest way I can come up with is to use default style in report and change its font name via java before you fill the report.

Example

Set a style (I will use default style) in jrxml, since this way I don't need to assign it to textField and it's quicker to get from JasperReport object

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="reputation" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a88bd694-4f90-41fc-84d0-002b90b2d73e">
    .....
   <style name="myStyle" isDefault="true" fontName="DejaVu Sans"/>
    ....
</jasperReport>

in java loaded your report (jrxml), change default style font name and then fill the report

JasperReport report = JasperCompileManager.compileReport("jmyReport.jrxml");
report.getDefaultStyle().setFontName("NewFontName");
JasperPrint jasperPrint = JasperFillManager.fillReport(report, paramMap,datasource);

Hower remember you need to add all your font's in Font Extensions!, if you like to ensure that they are rendered correctly in your pdf export on client machine.

You can also use non default style, in this case you need to assign it to textField and find it in the JRStyle[] styles = report.getStyles(); by comparing on JRStyle#getName()

like image 123
Petter Friberg Avatar answered Oct 09 '22 21:10

Petter Friberg