How to create a jasper pdf report from a json datasource in Java?

Today, I will be showing you how to easily create a jasper pdf report from a json datasource and how to pass parameters to jasper in Java. In this example, I will be reporting off the following simple small json array.

[ {"name":"Jerry", "value":"Jesus"}, {"name":"Gideon", "value": "Loves"}, {"name":"Eva", "value": "You"} ]

Setting Up Jasper Report In Jaspersoft Studio

Open up Jaspersoft Studo Community and create a new blank report. On the left hand outline pane, add the following

Parameters
title
name
value

Fields
name
value
Note: Make sure you name these fields the exact same as your json fields.

Now do the following.
1. Drag the parameters to the title and/or column header bands
2. Drag each field to the detail band.

Next, just click the build all toolbar button and jasper will compile your report. The compiled report will be named ending in .jasper.

In this example, I will be moving this compiled report to a directory called /home/jerry/ for simple demonstration. You can put this file anywhere your app has permission to read from.

Setting up java environment for Jasper development using gradle build tool

If you do not have gradle installed on your system, please install it now before you proceed. For instructions on installing gradle, go to https://gradle.org/.

The first thing we want to do is create the following directory structure.

When this is done create a file called build.gradle under the root of your project and put the following code in it.

apply plugin:'application'  
apply plugin: 'java'

repositories {  
    //tells gradle to look in maven for dependencies
    mavenCentral()
    //tells gradle to look for jasper artifacts in this repository
    maven {
        url 'http://jaspersoft.artifactoryonline.com/jaspersoft/third-party-ce-artifacts/'
    }
}
//configuration when creating jar file
jar {  
  //main class of jar file
  manifest {
    attributes "Main-Class": "JasperPDFExample"
  }
  //excludes all signed files when gradle creates jar
  from({configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) }}) {
    exclude "META-INF/*.SF"
    exclude "META-INF/*.DSA"
    exclude "META-INF/*.RSA"
  }
}
//external dependencies required for jasper
dependencies {  
  compile group: 'commons-codec', name: 'commons-codec', version: '1.9'
  compile group: 'org.apache.commons', name: 'commons-io', version: '1.3.2'
  compile group: 'org.apache.poi', name: 'poi', version: '3.10.1'
  compile group: 'net.sf.jasperreports', name: 'jasperreports', version: '6.3.0'
}
//tells gradle the main class of your java application
mainClassName = 'JasperPDFExample'  

Once this is complete, create a file called
JasperPDFExample.java file under the src/main/java/jasperpdfexample directory and put the following code in it. I went ahead and commented each line to explain what is happening.

import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;  
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;  
import net.sf.jasperreports.engine.export.JRHtmlExporter;  
import net.sf.jasperreports.engine.export.JRXlsExporter;  
import net.sf.jasperreports.engine.data.JsonDataSource;  
import net.sf.jasperreports.engine.JRExporterParameter;  
import net.sf.jasperreports.engine.JasperExportManager;  
import net.sf.jasperreports.engine.JasperFillManager;  
import net.sf.jasperreports.engine.util.JRLoader;  
import net.sf.jasperreports.engine.JasperReport;  
import net.sf.jasperreports.engine.JRException;  
import net.sf.jasperreports.engine.JasperPrint;  
import org.apache.commons.codec.binary.Base64;  
import java.util.HashMap;  
import java.util.Locale;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import java.io.*;

//Class Name. This must match the class name you put in your build.gradle file
public class JasperPDFExample {  
 public static void main(String[] args) {
  try {
   try {
    //Our json object. This can be loaded from file
    String rawJsonData = "[{\"name\":\"Jerry\", \"value\":\"Jesus\"},"
                       + "{\"name\":\"Gideon\", \"value\": \"Loves\"},"
                       + "{\"name\":\"Eva\", \"value\": \"You\"}"
                       + "]";
    //Load compiled jasper report that we created on first section.
    JasperReport report = (JasperReport) JRLoader.loadObject(new File("/home/jerry/Sample.jasper"));
    //Convert json string to byte array.
    ByteArrayInputStream jsonDataStream = new ByteArrayInputStream(rawJsonData.getBytes());
    //Create json datasource from json stream
    JsonDataSource ds = new JsonDataSource(jsonDataStream);
    //Create HashMap to add report parameters
    Map parameters = new HashMap();
    //Add title parameter. Make sure the key is same name as what you named the parameters in jasper report.
    parameters.put("title", "Jasper PDF Example");
    parameters.put("name", "Name");
    parameters.put("value", "Value");
    //Create Jasper Print object passing report, parameter json data source.
    JasperPrint jasperPrint = JasperFillManager.fillReport(report, parameters, ds);
    //Export and save pdf to file
    JasperExportManager.exportReportToPdfFile(jasperPrint,"/home/jerry/jasperpdfexample.pdf");
   } catch (JRException ex) {
    ex.printStackTrace();
    throw new RuntimeException(ex);
   } catch (Exception ex) {
    ex.printStackTrace();
    throw new RuntimeException(ex);
   }
  } catch (Exception ex) {
   ex.printStackTrace();
   throw new RuntimeException(ex);
  }
 }
}

Once this is done, you are ready to tell gradle to run your app. Before doing this, your directory structure should look like this.

From the root of your project, run the following command:

gradle run  

Gradle will then build the app and run your main class and when completed successfully, the pdf should be created and saved to the location you set in code. Here is how the pdf should look.

Conclusion

Creating a jasper pdf report from a json datasource in java is pretty straightforward. I found the hardest thing to this is the setup of Jasper java dependencies. I hope this blog helps someone get over the hurdle of using jasper in their current or next project.

Happy Coding!!!