Jasper reports are popular in Java world since they offer a simple way to export data into many formats - HTML, PDF, DOCX, XLS, XLSX, CSV, ODT, RTF and ODS. So, as you can see, the most commonly used filetypes are covered. In this tutorial, I'll show you how to create a Jasper PDF report using Java Beans & JRBeanCollectionDataSource and download this report over the REST service using HttpServletResponse. Source code is also available on GitHub, and here we'll go through example line by line. We'll create one simple bean with two attributes - name and color and use it to fill our simple report that will have only these two fields.  

Our design will look like this, so the simplest example, nothing fancy:

create jasper pdf using java beans

Dependencies

There's only one Maven dependency you should add: 

<dependency>
  <groupId>net.sf.jasperreports</groupId>
  <artifactId>jasperreports</artifactId>
  <version>6.12.2</version>
</dependency>

You can find a complete list of dependencies in the full project on GitHub

Implementation

In this example, we'll have two classes - first is Java Bean that we'll use as a data source and the second one is an example code where we'll create PDF file using our Jasper file and provided data source. 

So, this would be the bean class - it contains only fields and getters and setters.

public class SampleBean {
	
String name;
String color;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

And this is the exporter class.

package com.javahowtos.jasperdemo.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javahowtos.jasperdemo.beans.SampleBean;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

@RestController
@RequestMapping("api/document")
public class JasperDemoController {

@GetMapping()
public void getDocument(HttpServletResponse response) throws IOException, JRException {

String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperTemplate.jasper").getAbsolutePath();
// creating our list of beans
List<SampleBean> dataList = new ArrayList<SampleBean>();
SampleBean sampleBean = new SampleBean();
sampleBean.setName("some name");
sampleBean.setColor("red");
dataList.add(sampleBean);
// creating datasource from bean list
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
Map parameters = new HashMap();
JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "inline; filename=jasper.pdf;");
	}
}

Line by line explanation 

We'll need the location of our .jasper file that is placed in the resources folder of our Maven project, so we'll use ResourceUtils to get to the files' absolute path.

String sourceFileName = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "SampleJasperTemplate.jasper").getAbsolutePath();

The following part of code is just for building up the list of beans that will be provided as a data source to JRBeanCollectionDataSource. In case you don't want to pass a list of objects, but the only one instead, create it and add it to the list, Jasper will know how to deal with it. 

// creating our list of beans
List<SampleBean> dataList = new ArrayList<SampleBean>();
SampleBean sampleBean = new SampleBean();
sampleBean.setName("some name");
sampleBean.setColor("red");
dataList.add(sampleBean);
// creating datasource from bean list
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);

The parameter Map we provide is used for providing the report with some extra parameters. We currently don't need that, so we'll just pass the empty one.

JasperPrint object we create in the following line will be later used to create export to PDF stream that will be written to the HttpServletResponse's output stream:

JasperPrint jasperPrint = JasperFillManager.fillReport(sourceFileName, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());

It's important to give the resulting file the name and type so the browser can handle it easily (if you're using Postman to test this, click Send and Download instead just Send).

create jasper pdf using java beans

I'll also leave the full code of JRXML file in case someone needs it. Complete example can be found on GitHub.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.12.2.final using JasperReports Library version 6.12.2-75c5e90a222ab406e416cbf590a5397028a52de3  -->
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="fb6e4b8f-ea8e-4300-8083-71a78214b3f6">
	<queryString>
		<![CDATA[]]>
	</queryString>
	<field name="name" class="java.lang.String"/>
	<field name="color" class="java.lang.String"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<title>
		<band height="79" splitType="Stretch"/>
	</title>
	<pageHeader>
		<band height="35" splitType="Stretch"/>
	</pageHeader>
	<columnHeader>
		<band height="61" splitType="Stretch"/>
	</columnHeader>
	<detail>
		<band height="125" splitType="Stretch">
			<textField>
				<reportElement x="80" y="0" width="100" height="30" uuid="5148f13c-0494-43ec-bcf2-a5ad8d9ba8a6">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="e98fa7ab-2a98-457c-bfb9-50a3da760069"/>
				</reportElement>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="80" y="30" width="100" height="30" uuid="b164ba60-d460-4f05-9e87-382e99ae3ae5">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="4250a42b-493a-4eb4-b761-69690b62ef70"/>
				</reportElement>
				<textFieldExpression><![CDATA[$F{color}]]></textFieldExpression>
			</textField>
			<staticText>
				<reportElement x="0" y="-1" width="100" height="30" uuid="52a07475-051c-4f51-8193-6dc836ab2b01">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="e98fa7ab-2a98-457c-bfb9-50a3da760069"/>
				</reportElement>
				<text><![CDATA[name]]></text>
			</staticText>
			<staticText>
				<reportElement x="0" y="29" width="100" height="30" uuid="47ce10f8-1453-4437-bd25-994673a24a77">
					<property name="com.jaspersoft.studio.spreadsheet.connectionID" value="4250a42b-493a-4eb4-b761-69690b62ef70"/>
				</reportElement>
				<text><![CDATA[color]]></text>
			</staticText>
		</band>
	</detail>
	<columnFooter>
		<band height="45" splitType="Stretch"/>
	</columnFooter>
	<pageFooter>
		<band height="54" splitType="Stretch"/>
	</pageFooter>
	<summary>
		<band height="42" splitType="Stretch"/>
	</summary>
</jasperReport>

Pin It

Newsletter

Please enable the javascript to submit this form

Latest