JasperReports basic example

Hi everybody,

Today i have played around with JasperReports. Really nice java tool to created very easy reports. I did not find many examples on internet. Therefor I post my first try. I hope this will help other developers starting up with this great tool.

This example runs a query (JDBC connected) with some parameters define in Java. The result is converted to PDF and then zipped.

Test.java file


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.sql.Connection;
import java.sql.DriverManager;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;

/**
 * The Class Test.
 */
public class Test {

	/** The Constant LOG. */
	private static final Logger LOG = Logger.getLogger(test.class);
	
	/** The Constant BUFFER. */
	final static int BUFFER = 10240;
	
	/** The connection. */
	static Connection connection = null;

	/**
	 * Connect database.
	 */
	static void ConnectDatabase() {
		try {			
			// Load the JDBC driver
			String driverName = "oracle.jdbc.driver.OracleDriver";
			Class.forName(driverName);

			// Create a connection to the database
			String serverName = "127.0.0.1";
			String portNumber = "1521";
			String sid = "XE";
			String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
			String username = "test";
			String password = "test";
			connection = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			System.err.println("Could not find the database driver");
		} catch (Exception e) {
			System.err.println("Could not connect to the database");
		}
	}

	/**
	 * File zip.
	 */
	static void fileZip() {
		
		BufferedInputStream origin = null;
		try
		{
			FileOutputStream dest = new FileOutputStream("test.zip");
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[BUFFER];
			
			// get a list of files from current directory
			File f = new File("src/.");
			String files[] = f.list();

			for (int i=0; i<files.length; i++) {
			
				System.out.println("Adding: "+files[i]);
				FileInputStream fi = new FileInputStream("src/"+files[i]);
				origin = new BufferedInputStream(fi, BUFFER);
				ZipEntry entry = new ZipEntry(files[i]);
				out.putNextEntry(entry);
				int count;
				while((count = origin.read(data, 0, BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
     
	/**
	 * The main method.
	 * 
	 * @param args the arguments
	 */
	public static void main(String[] args) {
		JasperReport jasperReport;
		JasperPrint jasperPrint;
		
		long start = System.currentTimeMillis();
		
		try {			
			// Log log4j configuration
			final Properties log4jProperties = new Properties();
			log4jProperties.load(new FileInputStream("etc/log4j.properties"));
			PropertyConfigurator.configure(log4jProperties);
			
			LOG.info("Start");
			LOG.info("--------");
						
			LOG.info("Compile Jasper XML Report");
			jasperReport = JasperCompileManager.compileReport("src/test.jrxml");
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create Database connection");
			ConnectDatabase();
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create parameters");
			Map <String, Object> parameters = new HashMap<String, Object>();
			parameters.put("ReportTitle", "User Report");
			parameters.put("DataFile", "src/test1.jrxml");
			parameters.put("IdRange", 10);	
			
			LOG.info("Generated report");
			jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, connection);
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Generated PDF");
			JasperExportManager.exportReportToPdfFile(jasperPrint, "src/test.pdf");
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
			LOG.info("Create Zip File");
			fileZip();
			LOG.info("time : " + (System.currentTimeMillis() - start)+ " ms.");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		LOG.info("--------");
		LOG.info("Done");
	}
}

JaspersReports test.jrxml (Report template) file.

<?xml version="1.0"?>

<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="User Overview" pageWidth="595" pageHeight="842" columnWidth="515" leftMargin="40" rightMargin="40" topMargin="50" bottomMargin="50">


	<style name="Sans_Bold" isDefault="false" fontName="DejaVu Sans" fontSize="8" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
	<style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="8" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
	<style name="Title" style="Sans_Bold" fontSize="12"/>
	<style name="ColumnHeader" style="Sans_Bold" forecolor="white"/>
	
	<parameter name="ReportTitle" class="java.lang.String"></parameter>
	<parameter name="DataFile" class="java.lang.String"></parameter>
	<parameter name="IdRange" class="java.lang.Integer"></parameter>
	
	<queryString><![CDATA[SELECT id, displaynaam, puik_id FROM gebruiker WHERE id <=$P{IdRange} order by id]]></queryString>
	<field name="id" class="java.lang.Integer"/>
	<field name="displaynaam" class="java.lang.String"/>
	<field name="puik_id" class="java.lang.String"/>
	
	<title>
		<band height="70">
			<line>
				<reportElement x="0" y="0" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField isBlankWhenNull="true" bookmarkLevel="1">
				<reportElement x="0" y="10" width="515" height="30" style="Sans_Normal"/>
				<textElement textAlignment="Center">
					<font size="22"/>
				</textElement>
				<textFieldExpression class="java.lang.String"><![CDATA[$P{ReportTitle}]]></textFieldExpression>
				<anchorNameExpression><![CDATA["Title"]]></anchorNameExpression>
			</textField>
			<textField isBlankWhenNull="true">
				<reportElement x="0" y="40" width="515" height="20" style="Sans_Normal"/>
				<textElement textAlignment="Center">
					<font size="14"/>
				</textElement>
				<textFieldExpression class="java.lang.String"><![CDATA[$P{DataFile}]]></textFieldExpression>
			</textField>
		</band>

	</title>
	
	<pageHeader>
		<band height="15">
			<frame>
				<reportElement x="0" y="0" width="555" height="15" mode="Opaque" backcolor="black"/>
				<staticText>
					<reportElement x="5" y="0" width="155" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<text>Id</text>
				</staticText>
				<staticText>
					<reportElement x="125" y="0" width="100" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle"/>
					<text>Displaynaam</text>
				</staticText>
				<staticText>
					<reportElement x="270" y="0" width="60" height="15" style="ColumnHeader"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<text>PuikId</text>
				</staticText>
				</frame>
		</band>
	</pageHeader>
							
 <detail>
 	<band height="15">
			<frame>
				<reportElement x="0" y="0" width="555" height="15" />
				<textField>
					<reportElement x="5" y="0" width="155" height="15"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<textFieldExpression>$F{id}.toString()</textFieldExpression>
				</textField>
				<textField>
					<reportElement x="125" y="0" width="100" height="15"/>
					<textElement verticalAlignment="Middle"/>
					<textFieldExpression>$F{displaynaam}</textFieldExpression>
				</textField>
				<textField pattern="#,###.00">
					<reportElement x="270" y="0" width="60" height="15"/>
					<textElement verticalAlignment="Middle" textAlignment="Left"/>
					<textFieldExpression>$F{puik_id}</textFieldExpression>
				</textField>
			</frame>			
		</band>	
  </detail>
  
  <pageFooter>
		<band height="40">
			<line>
				<reportElement x="0" y="10" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField>
				<reportElement x="200" y="20" width="80" height="15"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="280" y="20" width="75" height="15"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
			</textField>			
		</band>
	</pageFooter>
  	
	<lastPageFooter>
		<band height="60">
			<textField bookmarkLevel="1">
				<reportElement x="0" y="10" width="515" height="15"/>
				<textElement textAlignment="Center"/>
				<textFieldExpression class="java.lang.String"><![CDATA["There were " + 
					String.valueOf($V{REPORT_COUNT}) + 
					" address records on this report."]]></textFieldExpression>
				<anchorNameExpression><![CDATA["Summary"]]></anchorNameExpression>
			</textField>
			<line>
				<reportElement x="0" y="30" width="515" height="1"/>
				<graphicElement/>
			</line>
			<textField>
				<reportElement x="200" y="40" width="80" height="15"/>
				<textElement textAlignment="Right"/>
				<textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
			</textField>
			<textField evaluationTime="Report">
				<reportElement x="280" y="40" width="75" height="15"/>
				<textElement/>
				<textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
			</textField>
		</band>
	</lastPageFooter>
		
</jasperReport>

Log4j.properties file

log4j.rootLogger=INFO, console, logfile
log4j.appender.logfile.File=../log/test.log

# Appender to log4j.log
log4j.appender.logfile=org.apache.log4j.RollingFileAppender
log4j.appender.logfile.MaxFileSize=1000KB
log4j.appender.logfile.MaxBackupIndex=9
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss,SSS} %-5p (%c:%L) - %M: %m%n
log4j.appender.logfile.Append=true

# Appender to Console
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss,SSS} %-5p (%c:%L) - %M: %m%n

4 thoughts on “JasperReports basic example”

Leave a Reply

Your email address will not be published. Required fields are marked *