Thursday, November 6, 2014

JasperReport scriptlet example.

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:
Picture 1: Obtain data through scriplet.
For create scriptlet you must do following:
  1. Create class which extended net.sf.jasperreports.engine.JRAbstractScriptlet or net.sf.jasperreports.engine.JRDefaultScriptlet.
  2. 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.
Get code with datasource and java code, which run report from my bitbucket repository or copy from article. Now add new class which extends JRDefaultScriptlet. JRAbstractScriptlet contains methods which called by event (e.g. callAfterDetailEval), methods which obtain data (getFieldValue, getParameterValue, getVariableValue) and methods for pass data into report (setData, setVariableValue).
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");
  }
}
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:

cd /path/to/ireport-subreport; mvn compile; mvn exec:java
If you do all right then will get result from Picture1.

Source code:

You can download source code from  BitBucket.

Related posts:

Resources




1 comment: