JasperReports is an open source
Java reporting tool that can write to a variety of targets, such as: screen, a
printer, into PDF, HTML, Microsoft Excel, RTF, ODT, Comma-separated values or
XML files.
Just compile and run the above file and click on the Generate Report link to download the generated PDF.
It can be used in Java-enabled
applications, including Java EE or web applications, to generate dynamic
content. It reads its instructions from an XML or .jasper file.
JasperReports reports are defined
in an XML file format, called JRXML, which can be hand-coded, generated, or
designed using tool Like IReport. The file format is defined by a
Document Type Definition (DTD) or XML schema for newer versions, providing
limited interoperability.
After compiling .jrxml file using
JasperCompileManager class, .jasper file created.
IDE Integration
Many prominent Java IDEs provide
instructions for users wishing to integrate JasperReports into a project.
NetBeans
iReport - a visual
designer for JasperReports
Eclipse
Jaspersoft Studio - a
re-write of iReport by the same team who originally developed iReport, backed
by Jaspersoft
JasperWave Report Designer
- free Eclipse-based visual editor for JasperReports report engine
IBM Websphere Studio Application Developer
This are the jar file required
for this project –
Required Jar |
This is my project structure –
Folder Structure |
These are the java files we create for this
example project-
SR#
|
Name
|
Description
|
1
|
JasperReport.jrxml
|
JasperReport Template File.
|
2
|
report.jsp
|
View from where user can generate
report.
|
3
|
JasperServlet.java
|
To handle request from JSP.
|
4
|
JasperData.java
|
To Get data from MySQL database.
|
5
|
JasperDataBean.java
|
Bean class to hold table data.
|
6
|
web.xml
|
Configuration file.
|
JasperReport.jrxml
This is jasper template; I used
ireport to create it, the objective of this blog is to see how jasper report
call from servlet, that is why we are not going deep in this report.
<?xml
version="1.0" encoding="UTF-8"?>
<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="test" pageWidth="595"
pageHeight="842"
columnWidth="535"
leftMargin="20"
rightMargin="20" topMargin="20"
bottomMargin="20"
uuid="a6b5b17a-e37b-4890-9fc9-fcc7cb06169c">
<property name="ireport.zoom"
value="1.0"/>
<property name="ireport.x"
value="0"/>
<property name="ireport.y"
value="0"/>
<style name="Title"
fontName="Arial" fontSize="26" isBold="true"
pdfFontName="Helvetica-Bold"/>
<style name="SubTitle"
forecolor="#666666" fontName="Arial"
fontSize="18"/>
<style name="Column header"
forecolor="#666666" fontName="Arial"
fontSize="12" isBold="true"/>
<style name="Detail"
fontName="Arial" fontSize="12"/>
<style name="table">
<box>
<pen lineWidth="1.0" lineColor="#000000"/>
</box>
</style>
<style name="table_TH"
mode="Opaque" backcolor="#F0F8FF">
<box>
<pen lineWidth="0.5"
lineColor="#000000"/>
</box>
</style>
<style name="table_CH"
mode="Opaque" backcolor="#BFE1FF">
<box>
<pen lineWidth="0.5"
lineColor="#000000"/>
</box>
</style>
<style name="table_TD"
mode="Opaque" backcolor="#FFFFFF">
<box>
<pen lineWidth="0.5"
lineColor="#000000"/>
</box>
<conditionalStyle>
<conditionExpression><![CDATA[new
Boolean($V{REPORT_COUNT}.intValue()%2==0)]]></conditionExpression>
<style
backcolor="#EFF7FF"/>
</conditionalStyle>
</style>
<parameter
name="paramLogFilePath" class="java.lang.String"/>
<queryString>
<![CDATA[]]>
</queryString>
<field name="addDate"
class="java.lang.String"/>
<field name="name" class="java.lang.String"/>
<field name="email" class="java.lang.String"/>
<field name="website"
class="java.lang.String"/>
<field name="subject" class="java.lang.String"/>
<field name="message"
class="java.lang.String"/>
<field name="recordStatus"
class="java.lang.String"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="68"
splitType="Stretch">
<image>
<reportElement
uuid="151fa442-13bd-4561-91e4-04867d3e0021" x="275"
y="0" width="300" height="64"/>
<imageExpression><![CDATA[$P{paramLogFilePath}]]></imageExpression>
</image>
<staticText>
<reportElement uuid="b4e32db9-4510-4452-9954-10dda6d4ed23"
style="Title" x="0" y="13" width="263"
height="33"/>
<textElement
verticalAlignment="Middle"/>
<text><![CDATA[JasperReport
Example]]></text>
</staticText>
<staticText>
<reportElement
uuid="f423a1a0-d4ef-4294-9d71-3d2e14e9d29d"
style="SubTitle" x="117" y="46"
width="157" height="22"/>
<textElement/>
<text><![CDATA[Vikas
Verma]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="36"
splitType
<line>
<reportElement
uuid="e16f96b6-7469-4d09-bc6a-763b4ca4a1c1"
positionType="FixRelativeToBottom" x="0" y="35"
width="555" height="1"/>
<graphicElement>
<pen lineWidth="0.5"
lineColor="#999999"/>
</graphicElement>
</line>
<staticText>
<reportElement
uuid="22d26c8a-c98c-4407-8682-0bdc501eabbe" x="0"
y="15" width="74" height="20"
forecolor="#999999"/>
<textElement>
<font size="11"
isBold="true"/>
</textElement>
<text><![CDATA[DATE]]></text>
</staticText>
<staticText>
<reportElement
uuid="9f47c603-ccea-4d41-8ec3-bbeeeed9d88f" x="84"
y="16" width="100" height="20" forecolor="#999999"/>
<textElement>
<font size="11"
isBold="true"/>
</textElement>
<text><![CDATA[NAME]]></text>
</staticText>
<staticText>
<reportElement
uuid="299942ac-837f-43c3-a398-e6be15ed9eb1" x="207"
y="16" width="100" height="20"
forecolor="#999999"/>
<textElement>
<font size="11"
isBold="true"/>
</textElement>
<text><![CDATA[EMAIL]]></text>
</staticText>
<staticText>
<reportElement uuid="08d67324-8b0b-479d-ba05-3cf7d115ebe1"
x="333" y="15" width="100" height="20"
forecolor="#999999"/>
<textElement>
<font size="11"
isBold="true"/>
</textElement>
<text><![CDATA[SUBJECT]]></text>
</staticText>
<staticText>
<reportElement
uuid="305b765a-0bba-4254-84c9-64c9756e4e7d" x="453"
y="16" width="100" height="20"
forecolor="#999999"/>
<textElement>
<font size="11"
isBold="true"/>
</textElement>
<text><![CDATA[MESSAGE]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="22"
splitType="Stretch">
<textField>
<reportElement
uuid="25736e6c-762f-4606-bf2e-95b4a09e734f" x="0"
y="0" width="74" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{addDate}]]></textFieldExpression>
</textField>
<textField>
<reportElement
uuid="974f11b2-36c2-4990-a4f0-fec7f9577063" x="84"
y="1" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField>
<reportElement
uuid="b3f6bff9-e25e-41b3-9c6a-42c654de68f2" x="208"
y="2" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
</textField>
<textField>
<reportElement
uuid="0149f58a-6872-46b8-be42-77e282f0c592" x="333"
y="2" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{subject}]]></textFieldExpression>
</textField>
<textField>
<reportElement
uuid="836eab83-b4a1-484f-9a35-2f43c08f7f8e" x="453"
y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$F{message}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height="45"
splitType="Stretch">
<line>
<reportElement
uuid="f74f05f1-d25c-4891-b570-450d0a554e35"
positionType="FixRelativeToBottom" x="0" y="3"
width="555" height="1"/>
<graphicElement>
<pen lineWidth="0.5"
lineColor="#999999"/>
</graphicElement>
</line>
</band>
</columnFooter>
<pageFooter>
<band height="20"
splitType="Stretch">
<textField>
<reportElement
uuid="a42a8c28-80d1-48d1-9285-64334068086b" style="Column
header" x="433" y="0" width="80"
height="20"/>
<textElement
textAlignment="Right">
<font size="10"
isBold="false"/>
</textElement>
<textFieldExpression><![CDATA["Page
"+$V{PAGE_NUMBER}+" of"]]></textFieldExpression>
</textField>
<textField
evaluationTime="Report">
<reportElement
uuid="911af05f-db59-47c7-8a82-7ce1f97be651" style="Column
header" x="513" y="0" width="40"
height="20"/>
<textElement>
<font size="10"
isBold="false"/>
</textElement>
<textFieldExpression><![CDATA[" " +
$V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
<textField pattern="EEEEE dd
MMMMM yyyy">
<reportElement uuid="1d95abb9-75cd-4319-836d-47810548f5ad"
style="Column header" x="0" y="0"
width="197" height="20"/>
<textElement>
<font size="10"
isBold="false"/>
</textElement>
<textFieldExpression><![CDATA[new
java.util.Date()]]></textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band splitType="Stretch"/>
</summary>
</jasperReport>
report.jsp
This JSP needed to call servlet.
<%@page
contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE
html>
<html>
<head>
<meta
http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JasperReport Download
Example</title>
</head>
<body>
<h1>
JasperReport Download Example
</h1>
<form name="jasper">
<a
href="JasperServlet" >
Generate Report
</a>
<br>
</form>
</body>
</html>
JasperServlet.java
/**
* Servlet class to
handle request from JSP and generate report.
*/
package servlet;
import com.data.JasperData;
import com.data.JasperDataBean;
import java.io.*;
import java.util.*;
import java.util.logging.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
/**
*
* @author Vikas
Verma
*/
public class JasperServlet extends HttpServlet {
/**
* Downloaded file
name.
*/
private String
DOWNLOAD_FILE_NAME = "REPORT.pdf";
/**
* File type.
*/
private String
FILE_TYPE = "application/pdf";
/**
* Processes
requests for both HTTP
*
<code>GET</code> and
*
<code>POST</code> methods.
*
* @param request
servlet request
* @param response
servlet response
* @throws
ServletException if a servlet-specific error occurs
* @throws
IOException if an I/O error occurs
*/
protected void
processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try {
/**
* Generate and
download pdf report.
*/
generateReport(request, response);
} catch
(Exception exp) {
exp.printStackTrace();
}
}
/**
* This method is
used to Generate and download JasperReport in pdf format.
*
* @param
HttpServletResponse object
*/
private void
generateReport(HttpServletRequest request,
HttpServletResponse response) {
/**
* Variable
Declaration.
*/
List<JasperDataBean> dataList;
String
reportPath;
OutputStream
outStream;
JasperReport
jasperReport;
JasperDesign
jasperDesign;
JRDataSource
reportSource;
JasperData jasperData;
String
logoFilePath;
Map
reportParameters;
try {
/**
* Get report
and logo file path.
*/
reportPath =
request.getServletContext().
getRealPath("reports")
+ "\\JasperReport.jrxml";
logoFilePath =
request.getServletContext().
getRealPath("reports")
+ "\\leaf_banner_gray.png";
/**
* Set report
parameters
*/
reportParameters = new HashMap();
reportParameters.put("paramLogFilePath", logoFilePath);
/**
* Compile
Jasper Report.
*/
jasperDesign =
JRXmlLoader.load(reportPath);
jasperReport =
JasperCompileManager.compileReport(jasperDesign);
/**
* Get report
DataSource.
*/
jasperData =
new JasperData();
dataList =
jasperData.getData();
reportSource = new
JRBeanCollectionDataSource(dataList);
/**
* Get
byteStream for generated Stream.
*/
byte[]
byteStream;
byteStream =
JasperRunManager.runReportToPdf(jasperReport,
reportParameters, reportSource);
/**
* Set output
Stream in response.
*/
outStream =
response.getOutputStream();
response.setHeader("Content-Disposition", "inline,
filename=" + DOWNLOAD_FILE_NAME);
response.setContentType(FILE_TYPE);
response.setContentLength(byteStream.length);
outStream.write(byteStream,
0, byteStream.length);
} catch
(JRException ex) {
Logger.getLogger(JasperServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch
(Exception e) {
e.printStackTrace();
}
}
// <editor-fold
defaultstate="collapsed" desc="HttpServlet methods. Click on the
+ sign on the left to edit the code.">
/**
* Handles the HTTP
*
<code>GET</code> method.
*
* @param request
servlet request
* @param response
servlet response
* @throws
ServletException if a servlet-specific error occurs
* @throws
IOException if an I/O error occurs
*/
@Override
protected void
doGet(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
*
<code>POST</code> method.
*
* @param request
servlet request
* @param response
servlet response
* @throws
ServletException if a servlet-specific error occurs
* @throws
IOException if an I/O error occurs
*/
@Override
protected void
doPost(HttpServletRequest request, HttpServletResponse response)
throws
ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short
description of the servlet.
*
* @return a String
containing servlet description
*/
@Override
public String
getServletInfo() {
return
"Short description";
}// </editor-fold>
}
JasperData.java
Before creating class to access DB, first create a table.
and insert sample data in the table -
delimiter $$
CREATE TABLE `message_header` (
`MESSAGE_ID`
int(11) NOT NULL AUTO_INCREMENT,
`NAME` varchar(50)
DEFAULT NULL,
`EMAIL` varchar(50)
DEFAULT NULL,
`website`
varchar(50) DEFAULT NULL,
`subject`
varchar(50) DEFAULT NULL,
`message`
varchar(500) DEFAULT NULL,
`record_status`
varchar(1) DEFAULT NULL,
`record_add_date`
date DEFAULT NULL
) ;
and insert sample data in the table -
INSERT INTO `jsr`.`message_header` (`MESSAGE_ID`, `NAME`,
`EMAIL`, `website`, `subject`, `message`, `record_status`, `record_add_date`)
VALUES ('19', 'abcd', 'abcd@abcd.com', 'www.abcd.abcd', 'this is subject',
'this is message', 'A', '2013-07-06');
Now create class to access this tables from Database.
/**
* This class is used
to get Data from DB.
*/
package com.data;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import servlet.JasperServlet;
/**
*
* @author Vikas
Verma
*/
public class JasperData {
/**
* Connection
settings.
*/
private final
String CONN_URL =
"jdbc:mysql://localhost/jsr?user=root&password=*****";
private final
String DRIVER =
"com.mysql.jdbc.Driver";
/**
* SQL Query.
*/
private final
String SQL =
" SELECT RECORD_ADD_DATE, NAME," +
" EMAIL, WEBSITE,SUBJECT, MESSAGE," +
" RECORD_STATUS" +
" FROM MESSAGE_HEADER" +
" ORDER
BY RECORD_ADD_DATE";
/**
* This method
return report data from MySQL DB
*
* @return List
object of Data Beans.
*/
public List
getData() {
JasperDataBean
objBean;
List<JasperDataBean> dataList = new
ArrayList<JasperDataBean>(0);
Connection conn;
PreparedStatement
ps;
ResultSet rs;
try {
/**
* Load Driver.
*/
Class.forName(DRIVER).newInstance();
/**
* Get data
from DB.
*/
conn =
java.sql.DriverManager.getConnection(CONN_URL);
ps =
conn.prepareStatement(SQL);
rs =
ps.executeQuery();
/**
* Populate
List of Data Bean.
*/
while
(rs.next()) {
objBean = new
JasperDataBean();
objBean.setAddDate(rs.getString("RECORD_ADD_DATE"));
objBean.setName(rs.getString("NAME"));
objBean.setEmail(rs.getString("EMAIL"));
objBean.setWebsite(rs.getString("WEBSITE"));
objBean.setSubject(rs.getString("SUBJECT"));
objBean.setMessage(rs.getString("MESSAGE"));
objBean.setRecordStatus(rs.getString("RECORD_STATUS"));
dataList.add(objBean);
}
} catch
(ClassNotFoundException ex) {
Logger.getLogger(JasperServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch
(InstantiationException ex) {
Logger.getLogger(JasperServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch
(IllegalAccessException ex) {
Logger.getLogger(JasperServlet.class.getName()).log(Level.SEVERE, null,
ex);
} catch
(SQLException ex) {
Logger.getLogger(JasperServlet.class.getName()).log(Level.SEVERE, null,
ex);
}
/**
* Return List of
data.
*/
return dataList;
}
JasperDataBean.java
/**
* JavaBean class to
hold DB data.
*/
package com.data;
/**
*
* @author Vikas
Verma
*/
public class JasperDataBean {
private String
addDate;
private String
name;
private String
email;
private String
website;
private String
subject;
private String
message;
private String
recordStatus;
public
JasperDataBean() {
}
public
JasperDataBean(String addDate, String name,
String email, String
website,
String subject,
String message, String
recordStatus) {
this.addDate =
addDate;
this.name = name;
this.email =
email;
this.website =
website;
this.subject =
subject;
this.message =
message;
this.recordStatus
= recordStatus;
}
public String
getAddDate() {
return addDate;
}
public void
setAddDate(String addDate) {
this.addDate =
addDate;
}
public String
getName() {
return name;
}
public void
setName(String name) {
this.name = name;
}
public String
getEmail() {
return email;
}
public void
setEmail(String email) {
this.email =
email;
}
public String
getWebsite() {
return website;
}
public void
setWebsite(String website) {
this.website =
website;
}
public String
getSubject() {
return subject;
}
public void
setSubject(String subject) {
this.subject =
subject;
}
public String
getMessage() {
return message;
}
public void
setMessage(String message) {
this.message =
message;
}
public String
getRecordStatus() {
return
recordStatus;
}
public void
setRecordStatus(String recordStatus) {
this.recordStatus
= recordStatus;
}
}
/* end of class */
web.xml
<servlet>
<description>For
Report 1</description>
<servlet-name>JasperServlet</servlet-name>
<servlet-class>servlet.JasperServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JasperServlet</servlet-name>
<url-pattern>/JasperServlet</url-pattern>
</servlet-mapping>
Just compile and run the above file and click on the Generate Report link to download the generated PDF.
Thanks
References -
http://en.wikipedia.org/wiki/JasperReports
good tutorial.
ReplyDeleteExcellent
ReplyDeletewhy didn't you put the java web code
ReplyDeleteHi, my jasper report from servlet is not showing up using jasperreportviewer. but the same report is working well within jasperstudio on same computer. can you help me?
ReplyDelete