I am using PHPExcel library to generate excel reports and PDF reports. Excel reports are generated fine and browser lets the user save the report. But when I use PHPExcel writer to generate a PDF using the tcpdf library, it doesnt prompt the user to save the PDF and shows binary characters on screen as shown below:
%PDF-1.7 %���� 8 0 obj << /Type /Page /Parent 1 0 R /LastModified (D:20130417151157+05'30') /Resources 2 0 R /MediaBox [0.000000 0.000000 792.000000 612.000000] /CropBox [0.000000 0.000000 792.000000 612.000000] /BleedBox [0.000000 0.000000 792.000000 612.000000] /TrimBox [0.000000 0.000000 792.000000 612.000000] /ArtBox [0.000000 0.000000 792.000000 612.000000] /Contents 9 0 R /Rotate 0 /Group << /
If I save the PDF on server, I can access it and view the report correctly using document viewer. Hence the PDF itself is not corrupt.
The code am using is
$rendererName = PHPExcel_Settings::PDF_RENDERER_TCPDF;
$rendererLibraryPath = 'library/tcpdf';
PHPExcel_Settings::setPdfRenderer(
$rendererName,
$rendererLibraryPath
);
$fullReportName = $reportName.".pdf";
$path = '/tmp/'.$fullReportName;
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
$objWriter->save($path);
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($path)); // File size
header('Content-Disposition: attachment;filename="'.$fullReportName.'"');
readfile($path);
Same behavior is seen if I use php://output directly from writer, instead of readfile as shown:
$objWriter->save('php://output');
How do I stop the binary from showing up and prompt the user for the file download?