Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JasperReports: How to add font not in the application classpath

I am trying to use a font, that is not installed on my local OS, with a JasperReports. The jasper report uses in this way:

<textField>  
  <reportElement x="0" y="0" width="137" height="20"/>  
        <textElement>  
    <font fontName="Corbel" size="12"/>  
    </textElement>  
    <textFieldExpression class="java.lang.String"><![CDATA[$F{something}]]></textFieldExpression>  
</textField>

The font named Corbel was exported as a font extension (using iReport) and is contained in file (Corbel.jar), in folder, on my system. I add this extension to the classpath of the application, using a code as follows:

ClassLoader cl = new URLClassLoader(new URL[] {new URL("file:///D:/path/to/Corbel_jar_folder/")});  
param = new HashMap();    
param.put(JRParameter.REPORT_CLASS_LOADER, cl);  
jasperReport = JasperCompileManager.compileReport("d:/path/to/Report_with_Corbel_font.jrxml");  
jasperPrint = JasperFillManager.fillReport(jasperReport, param, new JREmptyDataSource());

After the report is filled, I export it using a JRPdfExporter. However, in the result pdf file, the element does not have the Corbel font applied. I have not included the pdf exporting, because I think that the problem is somewhere with the filling. I have searched and read numerous posts and questions related to using/including fonts (i.e.font extensions) in JasperReports; still I am not aware of where the mistake or the problem resides. Any help would be greatly appreciated.

Thank you in advance! (sorry for the bad code indentation and I hope I have included enough details)

like image 663
acostache Avatar asked Jun 30 '10 17:06

acostache


1 Answers

The problem was that the loading of font extensions jars is done from the thread context classloader and from the JRParameter.REPORT_CLASS_LOADER, nor the JRExporterParameter.CLASS_LOADER.

Therefore, in my case, the current (initial) thread classloader had to be saved, the we had to do something like Thread.currentThread().setContextClassLoader(cl), where cl was the context of the JasperReports based application and then the thread context classloader was reverted to the original one.

The question has been answered and details are available here.

I hope this answer will help others facing similar (font) issues.

like image 175
acostache Avatar answered Sep 28 '22 02:09

acostache