背景
尝试通过 PHP 将使用 iReport 编写的 PDF 报告流式传输到浏览器。一般的问题是:如何使用 PHP 将二进制数据写入浏览器?
工作代码
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 );
非工作代码
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;
问题
如何取出写入文件的中间步骤,直接写入浏览器,以免 PDF 损坏?
更新
PDF 文件大小:
- 工作:594778字节
- 非工作:1059365 字节
谢谢!