如何将参数从PHP传递到JasperReports? [英] How to pass parameters from PHP to JasperReports?

查看:87
本文介绍了如何将参数从PHP传递到JasperReports?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Centos 5.5 final,Apache Tomcat 6,Java 1.6.0_24,PHP / Java Bridge 6.2.1和JasperReports 4.0.1。

Using Centos 5.5 final, Apache Tomcat 6, Java 1.6.0_24, PHP/Java Bridge 6.2.1, and JasperReports 4.0.1.

PHP无法将文本值添加到 java.util。 HashMap

PHP fails to add a text value to a java.util.HashMap.

是否有人对如何完成有任何建议这个任务?

Does any one have any suggestions on how to accomplish this task?

如果我注释掉行 $ map-> ; put(text,这是一个测试字符串); ,报告编译并运行。

If I comment out the line $map->put("text", "This is a test string");, the report compiles and runs.

<?php

/**
 * see if the java extension was loaded.
 */
function checkJavaExtension()
{
    if(!extension_loaded('java'))
    {
        $sapi_type = php_sapi_name();
        $port = (isset($_SERVER['SERVER_PORT']) && (($_SERVER['SERVER_PORT'])>1024)) ? $_SERVER['SERVER_PORT'] : '8080';
        if ($sapi_type == "cgi" || $sapi_type == "cgi-fcgi" || $sapi_type == "cli") 
        {
            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/java/Java.inc"))) 
            {
                return "java extension not installed.";
            }
        } 
        else
        {
            if(!(@include_once("java/Java.inc")))
            {
                require_once("http://www.webserver.net:$port/JavaBridge/java/Java.inc");
            }
        }
    }
    if(!function_exists("java_get_server_name")) 
    {
        return "The loaded java extension is not the PHP/Java Bridge";
    }

    return true;
}

/** 
 * convert a php value to a java one... 
 * @param string $value 
 * @param string $className 
 * @returns boolean success 
 */  
function convertValue($value, $className)  
{  
    // if we are a string, just use the normal conversion  
    // methods from the java extension...  
    try   
    {  
        if ($className == 'java.lang.String')  
        {  
            $temp = new Java('java.lang.String', $value);  
            return $temp;  
        }  
        else if ($className == 'java.lang.Boolean' ||  
            $className == 'java.lang.Integer' ||  
            $className == 'java.lang.Long' ||  
            $className == 'java.lang.Short' ||  
            $className == 'java.lang.Double' ||  
            $className == 'java.math.BigDecimal')  
        {  
            $temp = new Java($className, $value);  
            return $temp;  
        }  
        else if ($className == 'java.sql.Timestamp' ||  
            $className == 'java.sql.Time')  
        {  
            $temp = new Java($className);  
            $javaObject = $temp->valueOf($value);  
            return $javaObject;  
        }  
    }  
    catch (Exception $err)  
    {  
        echo (  'unable to convert value, ' . $value .  
                ' could not be converted to ' . $className);  
        return false;  
    }

    echo (  'unable to convert value, class name '.$className.  
            ' not recognised');  
    return false;  
}


checkJavaExtension();

$map = new Java("java.util.HashMap");
$map->put("text", "This is a test string");

$compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
$report = $compileManager->compileReport(realpath("test.jrxml"));





$fillManager = new JavaClass("net.sf.jasperreports.engine.JasperFillManager");





$emptyDataSource = new Java("net.sf.jasperreports.engine.JREmptyDataSource");
$jasperPrint = $fillManager->fillReport($report, $map, $emptyDataSource);

$outputPath = realpath(".")."/"."output.pdf";

$exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
$exportManager->exportReportToPdfFile($jasperPrint, $outputPath);

header("Content-type: application/pdf");
readfile($outputPath);

unlink($outputPath);

?>


推荐答案

来源



下面是根据用户输入字段的命名约定,自动将参数从PHP传递到JasperReports的代码。

Source

Here is some code to pass parameters from PHP to JasperReports automatically, based on a naming convention for user input fields.

<?php
include_once( 'db-account.php' );

checkjavaExtension();

function report_parse_post_parameters() {
  # Automatically extract report parameters (data types converted in report).
  $params = new java('java.util.HashMap');

  # Pass the remaining POST "report_TYP" variables as report parameters.
  foreach( $_POST as $name => $value ) {
    if( strpos( $name, 'report_' ) === 0 ) {
      $length = strlen( 'report_' );

      if( strpos( $name, 'report_int_' ) === 0 ) {
        $value = intval( $value );
        $length = strlen( 'report_int_' );

        $value = convertValue( $value, 'java.lang.Integer' );
        $params->put( substr( $name, $length ), $value );
      }
      else if( strpos( $name, 'report_arr_' ) === 0 ) {
        $length = strlen( 'report_arr_' );
        $arrays = array_filter( explode( ',', $_POST[ $name ] ) );

        # Map the values of the array form parameter to a java.util.ArrayList.
        $arrayList = new java( 'java.util.ArrayList' );

        foreach( $arrays as $value ) {
          $arrayList->add( $value );
        }

        # Pass values into the report (without the "report_arr_" prefix).
        $params->put( substr( $name, $length ), $arrayList );
      }
      else {
        $params->put( substr( $name, $length ), $value );
      }
    }
  }

  return $params;
}

function report_execute( $filename = 'FILENAME' ) {
  global $dbhost;
  global $dbname;
  global $dbuser;
  global $dbpass;

  $conn = null;
  $report = realpath( '/PATH/TO/REPORT.jasper' );

  try {
    $params = report_parse_post_parameters();

    # Load the PostgreSQL database driver.
    java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );

    # Attempt a database connection.
    $conn = java( 'java.sql.DriverManager' )->getConnection(
      "jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );

    # Use the fill manager to produce the report.
    $fm = java('net.sf.jasperreports.engine.JasperFillManager');
    $pm = $fm->fillReport($report, $params, $conn);

    header('Cache-Control: private');
    header('Content-Description: File Transfer');
    header("Content-Disposition: attachment, filename=$filename.pdf");
    header('Content-Type: application/pdf');
    header('Content-Transfer-Encoding: binary');

    java_set_file_encoding('ISO-8859-1');

    $em = java('net.sf.jasperreports.engine.JasperExportManager');
    $result = $em->exportReportToPdf($pm);

    $conn->close();

    header('Content-Length: ' . strlen( $result ) );
    echo $result;
  }
  catch( Exception $ex ) {
    if( $conn != null ) {
      $conn->close();
    }

    throw $ex;
  }
}
?>



用法



更改此行:

Usage

Change this line:

function report_execute( $filename = 'FILENAME' ) {

更改此行:

  $report = realpath( '/PATH/TO/REPORT.jasper' );

更改这些行以匹配您的数据库软件:

Change these lines to match your database software:

java( 'java.lang.Class' )->forName( 'org.postgresql.Driver' );
$conn = java( 'java.sql.DriverManager' )->getConnection(
  "jdbc:postgresql://$dbhost/$dbname?user=$dbuser&password=$dbpass" );

编辑 db-account.php

<?php
  $dbhost = 'HOSTNAME';
  $dbname = 'DATABASE';
  $dbuser = 'USERNAME';
  $dbpass = 'PASSWORD';
?>



示例表格输入



使用 report _ 用户输入的前缀,例如:

Example Form Input

Use a report_ prefix for user inputs, such as:

<form method="post" action='report.dhtml' class="climate" id="report-form">
  <input type="hidden" name="report_int_ReportId" value="1" />
  <input type="hidden" name="report_int_Radius" value="35" />
  <input type="hidden" name="report_int_Trend" value="0" />
  <input type="hidden" name="report_int_Relevance" value="1" />

  <select id="category" name="report_int_CategoryId" value="2"></select>
  <input type="text" id="city" name="report_int_CityId" />
  <input class="submit-button" id="submit" type="submit" name="submit" value="Report" />
</form>

然后这些值会自动传递到报告中。

These values are then passed automatically into the report.

您不必更改 checkjavaExtension()的代码。

这篇关于如何将参数从PHP传递到JasperReports?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆