Home Backend Development PHP Tutorial PHP通过PHP/JAVA Bridge调用JasperReport报表

PHP通过PHP/JAVA Bridge调用JasperReport报表

Jun 23, 2016 pm 02:29 PM

本文说到的是用PHP-Java-Bridge技术实现JasperReport web报表的输出。

JasperReport(http://jasperforge.org/),是一个强大、灵活的报表生成工具,能够展示丰富的页面内容,并将之转换成PDF,HTML,或者XML格式。该库完全由Java写成,可以用于在各种Java应用程序,包括J2EE,Web应用程序中生成动态内容。

附带报表设计工具是iReport(免费的),该工具可以实现可视化报表设计,可以输出PDF,HTML,WORD的常用格式报表,保存后的文件为.jrxml后缀,需要Java环境才可以正常运行,PHP不能直接调用。

既然PHP不能直接调用,这就不得不借助于PHP-Java-Bridge技术。具体可以参考http://php-java-bridge.sourceforge.net/pjb/index.php

1、安装tomcat,如果是选择exe安装版,安装的时候会自动安装jre环境,如果是压缩版tomcat,需要另外安装java环境,配置也更繁琐,推荐用安装版的tomcat。

把tomcat的端口配置6000,默认的8080端口被占用,站点根目录为tomcat下面的webapps

2、下载php-java-bridge包,地址http://php-java-bridge.sourceforge.net/pjb/download.php,下载后解压,里面有一个JavaBridge.war的文件,将这个文件拷贝到tomcat的webapps,运行http://localhost:6000/JavaBridge/之后,会在webapps生成一个JavaBridge的目录。

3、安装ireport3.0(有更新的版本) 拷贝C:\Program Files\JasperSoft\iReport-3.0.0\lib 中的所有内容,拷贝到tomcat的webapps/JavaBridge/WEB-INF/lib/下,这些包需要能被JavaBridge找得到才行。

4、从生成的JavaBridge目录下拷贝java目录到PHP站点下(或者找到php.ini这个文件,将里面的allow_url_include参数改为on,直接引用JavaBridge下的java/java.inc)。下载报表文件http://www.rjohnson.id.au/download/jasper/test.jrxml放在PHP站点下。

然后在PHP站点下建立一个PHP文件

ireport.php(代码中涉及到端口的,需要根据个人情况更改)

View Code

  1 <?php  2   3 /**  4  * see if the java extension was loaded.  5  */  6 function checkJavaExtension()  7 {  8     if(!extension_loaded('java'))  9     { 10         $sapi_type = php_sapi_name(); 11          12         //$port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'])>1024)) ? $_SERVER['SERVER_PORT'] : '6000'; 13         //echo $port; 14         $port = 6000; 15         if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" || $sapi_type == "cli")  16         { 17             if(!(PHP_SHLIB_SUFFIX=="so" && @dl('java.so'))&&!(PHP_SHLIB_SUFFIX=="dll" && @dl('php_java.dll'))&&!(@include_once("java/Java.inc"))&&!(require_once("http://127.0.0.1:$port/JavaBridge/java/Java.inc")))  18             { 19                 return "java extension not installed."; 20             } 21         }  22         else 23         { 24             if(!(@include_once("java/Java.inc"))) 25             { 26                  27                 require_once("http://127.0.0.1:$port/JavaBridge/java/Java.inc"); 28             } 29         } 30     } 31     if(!function_exists("java_get_server_name"))  32     { 33         return "The loaded java extension is not the PHP/Java Bridge"; 34     } 35  36     return true; 37 } 38  39 /**  40  * convert a php value to a java one...  41  * @param string $value  42  * @param string $className  43  * @returns boolean success  44  */   45 function convertValue($value, $className)   46 {   47     // if we are a string, just use the normal conversion   48     // methods from the java extension...   49     try    50     {   51         if ($className == 'java.lang.String')   52         {   53             $temp = new Java('java.lang.String', $value);   54             return $temp;   55         }   56         else if ($className == 'java.lang.Boolean' ||   57             $className == 'java.lang.Integer' ||   58             $className == 'java.lang.Long' ||   59             $className == 'java.lang.Short' ||   60             $className == 'java.lang.Double' ||   61             $className == 'java.math.BigDecimal')   62         {   63             $temp = new Java($className, $value);   64             return $temp;   65         }   66         else if ($className == 'java.sql.Timestamp' ||   67             $className == 'java.sql.Time')   68         {   69             $temp = new Java($className);   70             $javaObject = $temp->valueOf($value);   71             return $javaObject;   72         }   73     }   74     catch (Exception $err)   75     {   76         echo (  'unable to convert value, ' . $value .   77                 ' could not be converted to ' . $className);   78         return false;   79     } 80    81     echo (  'unable to convert value, class name '.$className.   82             ' not recognised');   83     return false;   84 } 85  86  87 checkJavaExtension(); 88  89 $compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager"); 90 $report = $compileManager->compileReport(realpath("test.jrxml")); 91  92 $fillManager = new JavaClass("net.sf.jasperreports.engine.JasperFillManager"); 93  94 $params = new Java("java.util.HashMap"); 95 $params->put("text", "This is a test string"); 96 $params->put("number", 3.00); 97 $params->put("date", convertValue("2007-12-31 0:0:0", "java.sql.Timestamp")); 98  99 $emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");100 $jasperPrint = $fillManager->fillReport($report, $params, $emptyDataSource);101 102 $outputPath = realpath(".")."/"."output.pdf";103 104 $exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");105 $exportManager->exportReportToPdfFile($jasperPrint, $outputPath);106 107 header("Content-type: application/pdf");108 readfile($outputPath);109 110 unlink($outputPath);111 112 ?>
Copy after login

5、访问PHP站点,http://localhost:8080/ireport.php,就可以输出PDF文档。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Working with Flash Session Data in Laravel Working with Flash Session Data in Laravel Mar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Simplified HTTP Response Mocking in Laravel Tests Simplified HTTP Response Mocking in Laravel Tests Mar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

12 Best PHP Chat Scripts on CodeCanyon 12 Best PHP Chat Scripts on CodeCanyon Mar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

PHP Logging: Best Practices for PHP Log Analysis PHP Logging: Best Practices for PHP Log Analysis Mar 10, 2025 pm 02:32 PM

PHP logging is essential for monitoring and debugging web applications, as well as capturing critical events, errors, and runtime behavior. It provides valuable insights into system performance, helps identify issues, and supports faster troubleshoot

HTTP Method Verification in Laravel HTTP Method Verification in Laravel Mar 05, 2025 pm 04:14 PM

Laravel simplifies HTTP verb handling in incoming requests, streamlining diverse operation management within your applications. The method() and isMethod() methods efficiently identify and validate request types. This feature is crucial for building

Discover File Downloads in Laravel with Storage::download Discover File Downloads in Laravel with Storage::download Mar 06, 2025 am 02:22 AM

The Storage::download method of the Laravel framework provides a concise API for safely handling file downloads while managing abstractions of file storage. Here is an example of using Storage::download() in the example controller:

See all articles