You are on page 1of 10

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).

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.llustration 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.

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

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.

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.

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 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

Comments (19)

1. Agung says:

February 19, 2008 at 2:31 pm


Good work Aris!
well Done, let’s do it men.
Agung Firdaus
ceo[at]jagadmaya.com
http://www.blog.firdaus.info

2. Integrating Jasper-Reports to PHP « Firdaus Blog says:

February 19, 2008 at 2:54 pm


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

3. HK says:

June 25, 2008 at 4:58 am


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

4. Php5 Dll says:

August 1, 2008 at 7:49 am


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

November 24, 2008 at 7:21 am


thanks pren

6. [PHP] PHP - Jasper Report Integeration | keyongtech says:

January 18, 2009 at 5:37 pm


[...] says "Unable to create Java Virtual Machine " Please refer this link for more details.
http://jagadmaya.com/integration-phpjasperreports.html — Regards, Johny [...]

7. Jagadmaya Solution - Integrating JasperReports to PHP says:

May 11, 2009 at 8:04 pm


[...] the original: Jagadmaya Solution – Integrating JasperReports to PHP Share and [...]

8. Nisha says:

May 17, 2009 at 11:01 pm


Hi,
I have referred this and have been trying to get jasper reports from php.
Some how the connection logic given above doesnt work for me. I even added mysql-java-connector.jar in
java_require() of php file.
But still it doesnt work.
Can you please what exactly should be done to get jdbc connection in php to pass it to fill Manager class. Is there
some special configuration for that.
Please help.
Thanks

9. Integrating Jasper-Reports to PHP - sebuah posting blog jagadmaya di digg.com | Alhaniin Blog - when miss is
everything says:
May 26, 2009 at 5:29 am
[...] carried out with the Jasper-Reports format from an application PHP via bridge PHP/JAVA Bridge. read more |
digg [...]

10. srikanth says:

June 10, 2009 at 11:25 am


Setup:
Windows
PHP 5.1.6
JasperServer-pro-3.5-windows-installer
MySQL 5
php-java-bridge_4.2.2_j2ee
i have modified Apache2 httpd.conf file and php.ini file.In PHP.ini file i changed extension_dir,and i added
extension=php_java.dll and “java” module.But i am getting a blank page.when i execute a program to get java
properties, i am getting output like
Java version=Object id #23
Java vendor=Object id #22
OS=Object id #7 Object id #23 on Object id #22
Wednesday, June 10, 2009 at 4:52:24 PM Central Daylight Time
but i am not getting java properties.
if anybody have idea could u please help me.
Thanks in advance.
Regards
srikanth

11. my blog says:


July 2, 2009 at 12:48 pm
check this out…
this is mine…
12. Kelvin Guzman says:

July 9, 2009 at 8:48 pm


Primeramente los quiero felicitar por su forma tan didáctica y fácil de tránsmitir sus conocimiento. El curso está
Excelente pocas pág hablan sobre este tema… Quería comentales el siguiente inconveniente que tuve. Les puedo
asegurar que realize todos los pasos anteriores de manera exacta varias veces para instalar el Puente PHP/JAVA y
NO me funciona, Estoy realizando un proyecto el cual tiene que imprimir un reporte (JasperReport) que consulta a la
base de datos MySQL, y no he logrado conectar el software que tengo en PHP con JasperReport, POR FAVOR
respondanme si alguien sabe como hacerlo este es mi correo kelvinguzman(arroba)hotmail.com Espero por su
respuesta… Tengo instalado el paquete de xampp 1.7.0 (creo que es el más actual) y Java JDK 1.7 Por Favor alguien
que me pueda ayudar ¿Porqué no me funciona el puente? ¿Será que puedo utilizar los applet de java como segunda
opción?

13. Nianlin says:

September 16, 2009 at 7:01 am


Actually, i have followed the way.
however, the lated PHP-java-bridge does not have the java-x86-windows.dll. a fast cgi file has been put there. do
they perform the same?
and after configure php.ini. the new section displaying java information doesn’t appear when i call phpinfo().
besides, i can invoke some simple java function and use it to show java version or OS info in a php page.
and when trying to get connection to DB, i wirte the statement in .java file because the DB i want to connect is a
fixed one. unfortunately, when i run the php page, it does not work. the driver can not be found. does it mean that
we must set connection variable from the php page?
thanks… and hope to hear from you soon.

14. kstan_79 says:

October 18, 2009 at 4:36 pm


My company’d develop a PHP class convert which can read iReport .jrxml and generate report on the fly. It is open
source base on FPDF! Feel free to try.
http://www.simit.com.my/?q=phpjasperxml
Due to I’m not active in here, you can place enquiry at my company sponsored forum afterwards.
Hope this help.
Ks

15. Watch Bleach says:

December 7, 2009 at 4:23 pm


Hi mate, this doesn’t look so enthusiastic on the Imperefct browser. But anyway keep up the writing.

16. Free Backlinks says:

December 11, 2009 at 1:43 pm


Hey good looking blog but it’s a little weird looking in my K-meleon browser. Looks great besides that!

17. Photoshop Brushes says:

December 17, 2009 at 10:23 am


Regards,

18. Albert Espericueta says:

December 23, 2009 at 9:28 am


This is an amazing entry. Thank you very much for the outstanding post provided! I was looking for this entry for a
long time, but I wasn
19. Lonnie Mccaughey says:

January 1, 2010 at 12:57 pm


Thanks very much for sharing this interesting post. I am just starting up my own blog and this has given me
inspiration to what I can achieve.

You might also like