Showing posts with label JasperReport. Show all posts
Showing posts with label JasperReport. Show all posts

Thursday, March 8, 2012

JasperReports with PHP

Today i am going to write this article on the use of JasperReports in PHP as a reporting tool. Here i have used IReport-4.5.0 IDE for designing the JasperReport Template (known as jrxml file).In addition, you require a PHP library(third party) that generates PDF reports from the given jrxml document. this library can be downloaded from the following Git Repository
https://github.com/chathurangat/PhpJasperLibrary

or else you can downloaded through following link


In order to design the template, please follow the steps given below.

1. load the IReport Designer tool
(executable file is available inside the bin directory)


2.after loading the IReport Tool,select new report template to start the report designing.
(File -> New)
then you will get a new window with a list of available report templates. select a template out of the available templates. in my case i have selected the Blank A4 template. please refer below.








then click the Launch Report Wizard to load the selected report template.



3. then give a Report Name and browse a Location where the report file (jrxml file) should be saved.  Please refer below.






4. then click on Next to proceed with next phase. please refer below.





 As you can see in the Screen-shot, you will be displayed a list of available data source connections that can be used in your report. if you wish to create a new data source connection, you are free to do so by clicking New button.


 5. if you click the New button to create new data source, you will be shown the below screen to select the the data source type. ( the data source type should be selected based on the application requirements. ) since this is PHP based web application, i have selected Database JDBC Connection as the data source type.



6. once you select the data source, click on next to proceed with next step. next will be the below screen.



here you have to provide the JDBC connection details.

 Name : just give any name for this connection for later reference  identification purpose


JDBC Driver:  select the most suitable JDBC driver from the given list based on your database. since i am using MySQL server database, i have selected  MySQL-JDBC Driver.


JDBC URL: make sure to edit the jdbc url based on your sever and database name. the default value of the jdbc url does not change, based on the value you provided for server and database. therefore please edit it manually.

Server Address : IP Address of the database sever. if the database is in your local machine, use localhost as IP.

Database : Database name that you are going to connect.


username: Username of the database server.

password : Password of the database server.


after filling all the configuration details, you can test the database conncetion by clicking the Test button provided. sometimes it may ask you to re-enter the database password. if the connection is successful, you will get a successful message as follows. then you can Save your new data source connection.





 7. then you can use your newly created data source for designing the query for your report. select the newly created data source and press Design Query button. then you will get the below window for designing the Query.


 
you will see a list of tables available in the connected database. you can Drag and Drop these tables to the provided area for designing the Query. then customize the columns displayed in the report by using the check boxes provided for each column.


8. once the Query is designed, press OK to finish it. the click Next to proceed with next phase. then next step is to select the required fields for your report out of the available all resulted columns of the Query you designed. add and remove the required database columns for your report with the provided button. please refer the below screen shot.




 9. after completing the above operation, you can press Next button for continue with next phase. next phase is for applying the Group By clause for the report view. then phase is optional and you can skip this step by clicking just Next button. then the initial process of the report design is finished and you will be notified with the below screen. jut click on finish button.



10. then it will load and display the created .jrxml file. you are required to remember that this is the file that contains your report template. you can design the report as you wish by providing preferable title, footer and other required fileds.


11. the designing utilities are available in the Report Inspector window. please refer below screen shot.


as you can see that the selected database column fields are available under the Fields. you can drag and drop the database fields in into the Detail1 Section of your Report.Once you drag a database field, its column header section will be automatically visible under Column Header section. In addition, the data field is visible under the Detail 1 Section. you can edit the column name as you wish.

12. Once the Design is done, you can preview the design using the Preview button. 


13. The Report design elements are available in the palette window. you can get the palette window Window -> Palette


14. Once all the design is done, the it is time to integrate with your PHP application. make sure to download and import the PhpJasperLibrary in your PHP script. (copy both .jasper and .jrxml files into a same directory and give the reference in the PHP script)


report_view.php

<?php

//Import the PhpJasperLibrary
include_once('PhpJasperLibrary/tcpdf/tcpdf.php');
include_once("PhpJasperLibrary/PHPJasperXML.inc.php");


//database connection details

$server="192.168.0.11";
$db="lcs_ims";
$user="web";
$pass="abc123@#";
$version="0.8b";
$pgport=5432;
$pchartfolder="./class/pchart2";


//display errors should be off in the php.ini file
ini_set('display_errors', 0);

//setting the path to the created jrxml file
$xml =  simplexml_load_file("report/chathuReport.jrxml");

$PHPJasperXML = new PHPJasperXML();
//$PHPJasperXML->debugsql=true;
//$PHPJasperXML->arrayParameter=array("parameter1"=>1);
$PHPJasperXML->xml_dismantle($xml);

$PHPJasperXML->transferDBtoArray($server,$user,$pass,$db);
$PHPJasperXML->outpage("I");    //page output method I:standard output  D:Download file


?>



access the report_view.php file in your LAMP/WAMP server. yo will get the report in PDF format.



Hope this will helpful for you!

Thanks and Regards,
Chathuranga Tennakoon
chathuranga.t@gmail.com



Wednesday, February 15, 2012

JasperReport with Spring MVC (fully working example with source code and explanation)

Today i am going to discuss how to integrate  jasper report with Spring MVC. i will be using following sample Spring MVC Application to show how the spring mvc and jasper report is integrated. you can download this application through following URL or GitHub repository.

https://github.com/chathurangat/spring-mvc-jpa-example

or

4shared URL

once you download the project, load it with your preferable development IDE. i have use Intelli J IDEA. the project structure is shown in the below screen shot.



the jasper report will be designed to display a list of Users who are already in the database(in User Table). this User table has been mapped to the User.java model that is available inside the org.convey.user.registration.model package. you can see the source code of the User.java model as follows.

User.java

package org.convey.user.registration.model;

import javax.persistence.*;
import java.util.Date;
import java.util.List;


@Entity
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    private int id;

    @Column(name = "username" , nullable = false , unique = true)
    private String userName;

    @Column(name = "password" , nullable = false)
    private String passWord;

    @Column(name = "email" , nullable = false , unique = true)
    private String email;

    @Column(name = "confirmation_code",length = 20)
    private String confirmationCode;

    @Column(name = "first_name" , length = 50,nullable = false)
    private String firstName;

    @Column(name = "last_name" , length = 50)
    private String lastName;

    @Column(name = "register_date")
    private Date registeredDate;

    @Column(name = "activate_status")
    private boolean  activate;

    @Version
    private int version;

    @ManyToMany
    @JoinTable(name ="user_module",
            joinColumns = {@JoinColumn(name = "userID", referencedColumnName = "user_id")},
            inverseJoinColumns = {@JoinColumn(name = "moduleID", referencedColumnName ="module_id")})
    private List<Module> modules;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getConfirmationCode() {
        return confirmationCode;
    }

    public void setConfirmationCode(String confirmationCode) {
        this.confirmationCode = confirmationCode;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getRegisteredDate() {
        return registeredDate;
    }

    public void setRegisteredDate(Date registeredDate) {
        this.registeredDate = registeredDate;
    }

    public boolean isActivate() {
        return activate;
    }

    public void setActivate(boolean activate) {
        this.activate = activate;
    }


    public List<Module> getModules() {
        return modules;
    }

    public void setModules(List<Module> modules) {
        this.modules = modules;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }

}//User




now it is the time to design the report using iReport. you can follow the below instructions to design your jasper report with iReport designer.

  • run the iReport tool. then File->New . then you will get the following set of available jasper report templates


  • In my case i have selected the Blank A4 report template. once you select the required report template, click Open this Template button to open the template.then you will get the following window.


then give a name for the report and select a location where the jrxml file should be saved.then click Next . after finishing all required operations you can see the selected template is loaded and ready o start the designing. please see the below.




if the palette is not automatically loaded in your designer, you can load it manually(window->palette)


you will see an another window called Report Inspector. you can add  the required fields for the report through this window. this can be done as follows.


right click on the Fields and select Add new Field Option.then you can see that newly added field is available under the Fields. you can change its attributes (name,type etc...) through the properties window. (Add up to four new fields)

Important:

when naming the fields, please make sure to name each field that is exactly same as the attribute name. In addition the data type (Field class) should also be same as the data type of identical attribute in the class. for more details, please see the below window. (we are going to design the report based on only the four attributes of the User class. therefore we need to create only four fields for the report). make sure to change the necessary properties of the newly added fields to reflect the below values.

attribute name(User class)     Field Name      Data Type(User class)     Field Class
 id                                              id                    int                                      Integer
 userName                                userName       String                                 String
 email                                        email               String                                 String
 firstName                                firstName        String                                 String


you can see that both attribute names and field names are identical. in addition there data types are also identical.now i assume that you have added new fields and changed their names and data types to meet above requirements. you can see all newly added fields as follows.



now you have loaded required components for your report design. now you can start  the design of your report. i will show you how to added newly created fields for your report.


drag and drop the newly added fields to the Detail 1 section of your report. please refer the below screen shot.



you can preview the design with the preview button.

now it is the time to start the jasper report integration with the spring mvc web application.suppose you have already downloaded the sample application given above for proceeding with this tutorial. you need to place the created jrxml file  in the class path. (in my case chathuranga-test-report.jrxml ).

 the jrxml file should be placed in the spring-mvc-jpa-jasper-report-example/src/main/resources location of the above downloaded project.

 then follow the instructions given below.

1. add the following maven dependencies to the pom.xml file.


<dependency>
            <groupId>net.sf.jasperreports</groupId>
            <artifactId>jasperreports</artifactId>
            <version>3.7.6</version>
            <type>jar</type>
            <scope>compile</scope>           
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.6</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>

        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
            <version>2.1</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>1.7.0</version>
        </dependency> 
 
 
2. add the following Report controller to your controller package.
(available in spring-mvc-jpa-jasper-report-example/src/main/java/org/convey/user/registration/controller )

ReportController.java

package org.convey.user.registration.controller;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.convey.user.registration.dao.UserDao;
import org.convey.user.registration.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



@Controller
@RequestMapping("/report/")
public class ReportController {


    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserDao userDao;

    @RequestMapping(method = RequestMethod.GET , value = "pdf")
    public ModelAndView generatePdfReport(ModelAndView modelAndView){

        logger.debug("--------------generate PDF report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //pdfReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("pdfReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "xls")
    public ModelAndView generateXlsReport(ModelAndView modelAndView){

        logger.debug("--------------generate XLS report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("xlsReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


    @RequestMapping(method = RequestMethod.GET , value = "csv")
    public ModelAndView generateCsvReport(ModelAndView modelAndView){

        logger.debug("--------------generate CSV report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("csvReport", parameterMap);

        return modelAndView;

    }//generatePdfReport



    @RequestMapping(method = RequestMethod.GET , value = "html")
    public ModelAndView generateHtmlReport(ModelAndView modelAndView){

        logger.debug("--------------generate HTML report----------");

        Map<String,Object> parameterMap = new HashMap<String,Object>();

        List<User> usersList = userDao.retrieveAllRegisteredUsers();

        JRDataSource JRdataSource = new JRBeanCollectionDataSource(usersList);

        parameterMap.put("datasource", JRdataSource);

        //xlsReport bean has ben declared in the jasper-views.xml file
        modelAndView = new ModelAndView("htmlReport", parameterMap);

        return modelAndView;

    }//generatePdfReport


}//ReportController





3. add the following jasper-view.xml file to the same directory where the applicationContext.xml file contains. (in this example, it is should be placed under the spring-mvc-jpa-jasper-report-example/src/main/webapp/WEB-INF/spring/app directory.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/util 
  http://www.springframework.org/schema/util/spring-util-3.0.xsd">

     <!--here all the url value should contains the valid path for the jrxml file-->
    
    <bean id="pdfReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsPdfView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="xlsReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsXlsView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="htmlReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource" />


    <bean id="csvReport"
          class="org.springframework.web.servlet.view.jasperreports.JasperReportsCsvView"
          p:url="classpath:chathuranga-sample-report.jrxml"
          p:reportDataKey="datasource"/>


</beans>

here all the url properties should contains the valid reference for a jrxml file that should be used as the report template.


4. then make the below XmlViewResolver bean declaration in your  applicationContext.xml file

    <beans:bean class="org.springframework.web.servlet.view.XmlViewResolver">
        <beans:property name="location" value="/WEB-INF/spring/app/jasper-views.xml"/>
        <beans:property name="order" value="0"/>
    </beans:bean>  

the value of location property should contains the reference for the xml file where the jasper view declarations are available.(in this case jasper-view.xml)


In addition, import the jasper-view.xml file to your applicationContext.xml file by placing the below import statement in your applicationContext.xml 


<beans:import resource="jasper-views.xml"/> 

Please make sure to change your database properties in the spring-mvc-jpa-jasper-report-example/src/main/resources/db.properties file.

then build your project with maven and deploy it in the tomcat server. then use following urls for getting the report you need.

PDF Report
 http://localhost:8080/common-user-registration/spring/report/pdf

XLS Report
 http://localhost:8080/common-user-registration/spring/report/xls

CSV Report
 http://localhost:8080/common-user-registration/spring/report/csv

HTML Report
 http://localhost:8080/common-user-registration/spring/report/html


you can download the fully example of this application through the  following git repository .

https://github.com/chathurangat/spring-mvc-jpa-jasper-report-example

Hope this will helpful for you !!!

Regards
Chathuranga Tennakoon
chathuranga.t@gmail.com