JasperReport can manipulate some views in depend from calculated data through report expression mechanism. But report expression has restriction - it must one-string code. So, you can't perform more complex functionality e.g. string manipulation. For such cases JasperReports provides scriptlets. Scriptlets - it java code which executed every time when report request.
Below I explain how obtain such result:
For create scriptlet you must do following:
Below code for manipulate values of NDoc field:
Now you must compile and register this code in JasperReport. In iReport go to java_beans_datasource_report properties and set Scriplet Class property to com.blogspot.mkazarian.ScripletMR. Next create scripletVar variable and set Variable Expression property to $P{REPORT_SCRIPTLET}.getDataSourceField().
Finally drag scripletVar from report inspector to Datail1 band. Save report and compile it with next command:
If you do all right then will get result from Picture1.
Below I explain how obtain such result:
Picture 1: Obtain data through scriplet. |
- Create class which extended net.sf.jasperreports.engine.JRAbstractScriptlet or net.sf.jasperreports.engine.JRDefaultScriptlet.
- Add compiled class to JasperReport classpath. In this article I will use code and datasource from this article, so my class will added to classpath automatically.
Below code for manipulate values of NDoc field:
package com.blogspot.mkazarian; import net.sf.jasperreports.engine.JRDefaultScriptlet; import net.sf.jasperreports.engine.JRScriptletException; /** * Class for demonstrate scriplet uses with master report. */ public class ScripletMR extends JRDefaultScriptlet{ /** * @return string with NDoc value. */ public String getDataSourceField() throws JRScriptletException { return "Obtain NDoc field value from scriptlet. It is " + this.getFieldValue("NDoc"); } }
Finally drag scripletVar from report inspector to Datail1 band. Save report and compile it with next command:
cd /path/to/ireport-subreport; mvn compile; mvn exec:java
Source code:
You can download source code from BitBucket.Related posts:
- Using JavaBean datasource for report and subreport in iReport.
- Runing JasperReport subreport from java code.
Resources
- JasperReports - Report Scriptlets
- JasperReports Scriptlet Example by Rodrigo De Castro
- Create Java Scriptlets for Jasper Reports
Thanks
ReplyDelete