Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

java - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...