Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write binary stream to browser using PHP

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

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');

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

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

$fh = fopen( $path, 'w' );
fwrite( $fh, $result );
fclose( $fh );

readfile( $path );

Non-working Code

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');

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

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

echo $result;

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?

Update

PDF file sizes:

  • Working: 594778 bytes
  • Non-working: 1059365 bytes

Thank you!

like image 466
Dave Jarvis Avatar asked May 08 '10 04:05

Dave Jarvis


1 Answers

I've previously experienced problems writing from Java because it'll use UTF-16. The function outputPDF from http://zeronine.org/lab/index.php uses java_set_file_encoding("ISO-8859-1");. Thus:

  java_set_file_encoding("ISO-8859-1");

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

  header('Content-Length: ' . strlen( $result ) );

  echo $result;
like image 165
Paolo Avatar answered Oct 09 '22 16:10

Paolo