E-learning - Written by Aries on Tuesday, February 19, 2008 5:31 - 4 Comments

Integrating JasperReports to PHP

PHP/JasperReports Integration

The purpose of this document is to explain how to implement the call of reports/ratios carried out with the JasperReports format from an application PHP via bridge PHP/JAVA Bridge.

I Introduction

PHP gained years by years an image of professional, simple and powerful language. As the French Association of the Users of PHP in his White Paper shows it “PHP in Company” (1), there is a very great number of Internet sites of reputation, companies of the CAC 40 which develops in PHP. What reinforces this image of robustness then. This notoriety of the language is also visible taking into account the number of articles which is devoted to him, and numbers it very important the research carried out on Google(2).

image001.jpg
Illustration 1: Google Trends: JAVA, PHP, NET, PYTHON

There are some bookshops of good level for the production of graphs, of documents to format pdf However, little of them provide an environment to assist the originators of reports/ratios in their development and their publication. Agatha Carryforwards (3), a Brésilien project has the ambition to bring to PHP the tools for reporting which it misses. This solution although functional calculus does not support PHP5 to date (4). In the same way, the new platform of Zend in version 3.0.2 (5) poster a support for BIRT(6), an environment of design of report/ratio based under Eclipse and supported by Actuate.

Jasper Reports offered to the world Java TM an engine of great quality for the generation of reports/ratios gathering tables, graphs, mixing with the very heterogeneous data sources (report/ratio multi-source). This tool in more of being very powerful can export towards various formats such as: pdf, HTML, xls, xml, cvs, txt, rtf and in particular a support for Open Office since its last version. In addition, iReport, an environment of development Jasper Carryforwards gets a high level assistance in the construction of the other reports/ratios or states. Moreover, the two projects follow a synchronized evolution. Thus, all the functionalities added to the engine Jasper Carryforwards are taken into account by iReport.

Many are the interrogations posted on the forums on the tools for reporting in PHP, or on the integration between PHP and of the third environment of reporting. Here is an answer: “PHP and To marble Carryforwards”! This one seems to us elegant because it brings productivity, thanks to iReport which is rather simple to take in hand then avoiding learning the API one from the bookshop. Then, Jasper Carryforwards is an engine now tested: many free solutions or owners embark it, of the large companies like Siemens, the French administrations make a use of it regular. Lastly, association PHP, Java, via PHP/Java Bridge (7) starts to gain its gallons. Even if some think that there are margins of improvement (8). This project makes possible the instanciation of java objects since programs PHP with syntax PHP.

You included/understood it to integrate reports/ratios Jasper Carryforwards into your programs PHP it is necessary to install PHP/Java Bridge.

II. Installation of PHP/Java Bridge

II-A. installation under GNU Linux

The installation under GNU Linux is rather simple bus the packages are available to the format rpm. It is advisable to download the file php-java-bridge-x.y.z-1-i386.rpm and to install it:

file rpm for the installation of the bridge between php and java
rpm -i php-java-bridge-x.y.z-1- i386.rpm

where “x.y.z” corresponds to the last stable version.

Of course it is necessary to have a virtual machine Java installed on her machine. In the file php.ini it is at least necessary to initiate the variable java.java. You must in your file php.ini (or php.d/java.ini) add the entries:

configuration of the file php.ini
java.java_home= {Repertory D’installation JAVA} java.java={Répertoire d’JAVA installation

where {Répertoire of installation JAVA} is to be replaced by the way towards your intallation of the SDK.

If you wish to make dialogue your applications PHP and a waiter J2EE to install the package php-java-bridge-tomcat:

file rpm to exploit an interface with tomcat
rpm -i php-java-bridge-tomcat-x.y.z-1i386.rpm

To download the adequate files to see: http://sourceforge.net/project/showfiles.php?group_id=117793

II-B. installation under Windows

Here, it is necessary to download php-java-bridge_y.x.z_j2ee.zip, to decompress it in a temporary repertory. Among the which decompressed files there is a file Web JavaBridge.war . Also decompress and copy the files JavaBridge.jar and java-x86-windows.dll respectively since Web-INF/lib and Web-INF/cgi in the repertory of your extension php. Lastly, you should add some entries in your file php.ini.

configuration php.ini
Extension=php_java.dll

Your file php.ini integrates the preceding line then and is close to what follows:

configuration php.ini
; windows Extensions ; Note that ODBC support is built in, so no dll is nedded for it.; Note that mny DLL files are located in the extensions/ (PHP 4) ext. (PHP 5)……;extension-php_mbstring.dll;extension-php_bz2.dll……extension-php_java.dll……

Finally configure the Java connector for PHP

configuration php.ini
;;;;;;;;;;;;;;;;;;; ; Module Settings ;;;;;;;;;;;;;;;;;;;;[java]java.java_home = “c:\Program File\Java\jdk1.50_10\bin “java.java =” c:\Program File\Java\jdk1.50_10\bin\javaw.exe “java.class.path=” c:\php\ext\JavaBridge.jar “java.library.path =” c:\php\ext “;java.hosts =”127.0.0.1:8080″;java.servlet = One java.log_level = 2

Of course the various variables are to be initialized with the values relative to your evironnement Java (the repertory where is installed your SDK), or of your waiter of application J2EE.

for more iformations: http://www.dsl.uow.edu.au/~sk33/php5java.htm

II-C. checking of the support java of PHP

You must start again your waiter apache and check that you have well the support java of PHP.

Create a phpinfo.php page and insert there the following lines:

phpinfo()
<?php phpinfo();?>

Save this file, publish it on your environment Web, and call the page since your navigator. You will have to observe the support java of php.

image002.jpg

Illustration 4: modulate php/java bridge

II-D. your first integration between PHP and Java

Create a file java.php and stick the following lines:

call of java since php
<?php $system = new Java’java.lang.System’);echo ‘Java version=’ . $system->getProperty(’java.version’) . ‘ <br />’;echo ‘Java vendor=’ . $system->getProperty(’java.vendor’) . ‘<br />’;echo ‘OS=’ . $system->getProperty(’os.name’) . ‘ ‘ .$system->getProperty(’os.version’) . ‘ on ‘ .$system->getProperty(’os.arch’) . ‘<br />’;// Example java.util.Date$formater = new Java’java.text.SimpleDateFormat’,“EEEE, MMMM dd, yyyy ‘at’ h:mm:ss a zzzz”);echo $formater->format(new Java’java.util.Date’));?>

Record this Web page and call since your navigator.

image003.jpg

Illustration 5: the first integration between php and java

III. Call of the JasperReports files since PHP

III-A. to build your model of document with iReport

image004.jpg

Illustration 6: iReport 1.3.3

Thanks to iReport you will be able to build your report/ratio:

  1. define your connection to your data base or another data source
  2. create a new document
  3. create a request with the assistant
  4. Add the elements which you wish with your report/ratio
  5. Record your report/ratio
  6. Carry out the report/ratio.

III-B. to write the script PHP which calls your file JRXML

In the example which follows we will proceed to instanciations of the classes of the API java To marble Carryforwards while following the stages generally indicated in the examples provided by their demonstration.

image005.jpg

Illustration 7: API To marble Carryforwards: flow of generation

Create a file which you can for example name jasperreports.php and add the following lines:

JasperReports since a script php
<?php $reportsPath =”/home/ccharly/publichtml/utils/reports/”;$reportFileName = “CommandesClients1″;$jasperReportsLib = “/home/ccharly/publichtml/utils/jasperlib”;if(extension_loaded(’java’)) {$handle = @to opendir($jasperReportsLib);while(($new_item = to readdir($handle))!==false) {$java_library_path .= ‘file:’.$jasperReportsLib.’/’.$new_item .’;';}try {java_require($java_library_path);$Conn = new Java”org.altic.jasperReports.JdbcConnection”);// driver $Conn->setDriver(”com.mysql.jdbc.Driver”);// url de connexion$Conn->setConnectString(”jdbc:mysql://localhost/erpmart”);$Conn->setUser(”root”);// mot de passe

$Conn->setPassword(null);

$sJcm = new JavaClass(”net.sf.jasperreports.engine.JasperCompileManager”);

$report = $sJcm->compileReport($reportsPath .$reportFileName.”.jrxml”);

$sJfm = new JavaClass(”net.sf.jasperreports.engine.JasperFillManager”);

$print = $sJfm->fillReport(

$report,

new Java”java.util.HashMap”),

$Conn->getConnection());

$sJem = new JavaClass(”net.sf.jasperreports.engine.JasperExportManager”);

$sJem->exportReportToPdfFile($print, $reportsPath .$reportFileName.”.pdf”);

if (file_exists($reportsPath .$reportFileName.”.pdf”)){

header(’Content-disposition: attachment; filename=”‘.$reportFileName.’.pdf”‘);

header(’Content-Type: application/pdf’);

header(’Content-Transfer-Encoding: binary’);

header(’Content-Length: ‘. @filesize($reportsPath . $reportFileName.”.pdf”));

header(’Pragma: no-cache’);

header(’Cache-Control: must-revalidate, post-check=0, pre-check=0′);

header(’Expires: 0′);

set_time_limit(0);

@readfile($reportsPath .$reportFileName.”.pdf”) or die(”problem occurs.”);

}

} catch (JavaException $ex) {

$trace = new Java”java.io.ByteArrayOutputStream”);

$ex->printStackTrace(new Java”java.io.PrintStream”, $trace));

print “java stack trace: $trace\n”;

}

}

?>

You must adapt the file by modifying the following variables:

$reportsPath : way where your reports/ratios with the format jrxml are arranged

$reportFileNamE: name of the file to be compiled and export in pdf (note: here only the root of the name of the file is necessary)

$jasperReportsLib : repertory of the bookshops necessary to the use of JasperReports. This repertory contains for example the same bookshops as those contained in the repertory lib of iReport.

The order java_require load in the classpath all these bookshops. Take care that the repertory indicated by $jasperReportsLib is accessible to the user who makes turn apache as well as the files that it contains.

Add the file alticJasper.jar it contains a small utility to create a connection JDBC.

classify connection JDBC
package org.altic.jasperReports; import java.io.FileInputStream;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;/*** @author ccharly**/public class JdbcConnection {private String driver; // “oracle.jdbc.driver.OracleDriver”;private String connectString; // “jdbc:oracle:thin:@YOUR_ORACLE_HOST:1521:YOUR_SID”;private String to use; //”YOUR_ORACLE_USER_NAME”;private String password; // “YOUR_ORACLE_PASSWORD”;public JdbcConnection(){//loadPropertiesConnection();}

public JdbcConnection(String driver, String connectString,

String to use, String password){

thisdriver = driver;

thisconnectString = connectString;

thisuser = to use;

thispassword = password;

}

public void loadPropertiesConnection(){

thisdriver = “”;

thisconnectString = “”;

thisuser = “”;

thispassword = “”;

try {

Properties props = new Properties(); InputStream resourceAsStream = getClass().getResourceAsStream(”/connection.properties”); props.load(resourceAsStream);

this.setDriver(props.getProperty(”driver”));

this.setConnectString(props.getProperty(”connectString”));

this.setUser(props.getProperty(”user”));

this.setPassword(props.getProperty(”password”));

}catch(Exception E){

E.printStackTrace();

}

}

public Connection getConnection()

{

try {

//Change these settings according to your local configuration

Class.forName(this.getDriver()); Connection conn = DriverManager.getConnection(

this.getConnectString()

this.getUser()

this.getPassword());

return conn;

}catch(ClassNotFoundException E){

E.printStackTrace();

}catch(SQLException E){

E.printStackTrace();

}

return null;

}

public String toString(){

return ” Driver : ” + this.getDriver() + ” | ” +

” ConnectString : ” + this.getConnectString() + ” | ” +

” User : ” + this.getUser() + ” | ” +

” Password : ” + this.getPassword();

}

public String getConnectString() {

return connectString;

}

public void setConnectString(String connectString) {

thisconnectString = connectString;

}

public String getDriver() {

return driver;

}

public void setDriver(String driver) {

thisdriver = driver;

}

public String getPassword() {

return password;

}

public void setPassword(String password) {

thispassword = password;

}

public String getUser() {

return to use;

}

public void setUser(String to use) {

thisuser = to use;

}

}

You must thus modify the parameters of connections towards your data base. Also think of adding the bookshop of connector JDBC towards your data base.

Indicate driver JDBC of your data base, for example for MySql

configuratioin of a connection JDBC since PHP - 2
$Conn->setDriver(”com.mysql.jdbc.Driver”);

Indicate the URL of connection

configuratioin of a connection JDBC since PHP - 2
$Conn->setConnectString(”jdbc:mysql://{Nom du S}:{port}/{Nom de la Base de données}”);

Indicate the name of the user

configuratioin of a connection JDBC since PHP - 3
$Conn->setUser({user};

Indicate the password

configuratioin of a connection JDBC since PHP - 4
$Conn->setPassword({Password});

Once these parameter settings finished, you are able to generate your JasperReports reports/ratios since PHP. Compilation is undoubtedly not useful if you to directly publish the files “jasper” which you can recover since iReport.

image006.jpg

Illustration 8: remote loading of the generated file

IV. Conclusion

This small example shows how it is thus possible to exploit JasperReports via an application PHP. This integration brings to PHP a tool for powerful and particularly productive reporting thanks to iReport. The originators of reports/ratios finds themselves in a convivial and productive environment.

To increase the productivity for this reason it would be interesting to encapsulate JasperReports in order to mask complexity of it not to reject the users of PHP already accustomed to a relatively simple syntax. Let us take for example the connection towards the data base one would need a line of code which would be:

to simplify connection JDBC - 1
$conn->getMySqlConnection({name of the Waiter}, {Port}, {Bases user data}, {}, {Password});

or

to simplify connection JDBC - 2
$conn->getConnection({basic Type},{name of the Waiter}, {Port}, {Bases user data}, {}, {Password});

where {Type basic} would be worth: ORACLE, MYSQL, POSTGRESQL

The encapsulation would also avoid with developers PHP having to handle the direct calls with the classes java, which would simplify the reading of the code of it.

The Dynamic project To marble offer a simplification of API JasperReports. It would be interesting to be based on this project to develop a bookshop of scripts PHP for JasperReports.

 

 

Translated from www.charly-clairmont.developpez.com

Go back to publication: 01/06/2007, Date of update: 24/08/2007 By Charly Clairmont (Site perso)

To go further

PHP/Java Bridge in http://php-java-bridge.sourceforge.net/pjb

Jasper Reports and PHP It is a very good article which brings already a certain abstraction of complexity To marble Carryforward in PHP. It is necessary I think of going even further. But it is a very good beginning. http://www.rjohnson.id.au/wordpress/2007/02/04/jasper-carryforwards-and-php/

Project To marble Carryforwards http://jasperforge.org/sf/projects/jasperreports

Project iReport http://jasperforge.org/sf/projects/ireport

PHP and BEA Weblogic http://dev2dev.bea.com/pub/a/2007/02/php-java-bridge.html

Courses on the generators of states - on Developpez.com http://etats.developpez.com

Integration of FOP and PHP/Java Bridge http://wiki.apache.org/xmlgraphics-fop/HowTo/PHPJavaBridge

Dynamic To marble http://dynamicjasper.sourceforge.net/

(1) Deliver Blanc “PHP in company” - http://php.developpez.com/etudes/livre-white-php-company
(2) http://google.fr/trends?q=java, php, python, net&ctab=0&geo=all&date=all&sort=0
(3) http://www.agata.org.br/
(4) http://groups.google.fr/group/comp.lang.php/browse_thread/thread/b9e178b19c135cca/ba59aa035b6e4b8f
(5) http://www.zend.com/fr/products/zend_platform/what_s_new
(6) http://www.eclipse.org/birt/phoenix/ - http://birtworld.blogspot.com
(7) http://php-java-bridge.sourceforge.net/pjb/index.php
(8) http://www.clever-age.com/veille/blog/retour-D-experiment-on-php-java-bridge.html


4 Comments

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Agung
Feb 19, 2008 14:31

Good work Aris!
well Done, let’s do it men.

Agung Firdaus
ceo[at]jagadmaya.com
http://www.blog.firdaus.info

Integrating Jasper-Reports to PHP « Firdaus Blog
Feb 19, 2008 14:54

[…] carried out with the Jasper-Reports format from an application PHP via bridge PHP/JAVA Bridge.read more | digg story addthis_url = […]

HK
Jun 25, 2008 4:58

terima kasih tutorialnya saya dah berhasil. sekarang gimana caranya biar muncul print viewer nya manggil class nya gimana, bisa kasih contoh lagi untuk menampilkan print viewer nya, jangan langsung export ke pdf

terima kasih

Php5 Dll
Aug 1, 2008 7:49

I found your site on faves.com bookmarking site.. I like it ..gave it a fave for you..ill be checking back later

Leave a Reply

Comment

Jagadmaya Site Contents

E-learning - Feb 19, 2008 5:31 - 4 Comments

Integrating JasperReports to PHP

More In E-learning


News - Feb 12, 2008 8:33 - 1 Comment

Jagadmaya Has Been Promoted as Google Apps ISP Partner

More In News


Jobs - Mar 10, 2008 14:09 - 1 Comment

[Urgently required] php programmer base location Jakarta

More In Jobs