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!
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With