Write binary stream to browser using PHP

Posted by Dave Jarvis on Stack Overflow See other posts from Stack Overflow or by Dave Jarvis
Published on 2010-05-08T04:43:02Z Indexed on 2010/05/08 4:48 UTC
Read the original article Hit count: 403

Background

Trying to stream a PDF report written using iReport through PHP to the browser. The general problem is: how do you write binary data to the browser using PHP?

Working Code

The following code does the job, but (for many reasons) it is not as efficient as it should be (the code writes a file then sends the file contents the browser).

// Load the MySQL database driver.
//
java( 'java.lang.Class' )->forName( 'com.mysql.jdbc.Driver' );

// Attempt a database connection.
//
$conn = java( 'java.sql.DriverManager' )->getConnection(
  "jdbc:mysql://localhost:3306/climate?user=$user&password=$password" );

// Extract parameters.
//
$params = new java('java.util.HashMap');
$params->put('DistrictCode', '101');
$params->put('StationCode', '0066');
$params->put('CategoryCode', '010');

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

header('Cache-Control: no-cache private');
header('Content-Description: File Transfer');
header('Content-Disposition: attachment, filename=climate-report.pdf');
header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . strlen( $result ) );

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

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

readfile( $path );

$conn->close();

Non-working Code

To remove the slight redundancy (i.e., write directly to the browser), the following code looks like it should work, but it does not:

$em = java('net.sf.jasperreports.engine.JasperExportManager');
$result = $em->exportReportToPdf($pm);
header('Content-Length: ' . strlen( $result ) );

echo $result;

Content is sent to the browser, but the file is corrupt (it begins with the PDF header) and cannot be read by any PDF reader.

Question

How can I take out the middle step of writing to the file and write directly to the browser so that the PDF is not corrupted?

Thank you!

© Stack Overflow or respective owner

Related posts about php

Related posts about php-java-bridge