Dave Jarvis
Dave Jarvis

Reputation: 31201

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:

Thank you!

Upvotes: 6

Views: 4848

Answers (2)

Paolo
Paolo

Reputation: 1573

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;

Upvotes: 2

cherouvim
cherouvim

Reputation: 31918

You just write the output. Make sure that:

  • correct headers have been set
  • no other character have been accidentally printed before or after the binary (this includes whitespace).

Upvotes: 0

Related Questions