PHP Nuisance: How to Stream PDF Files
If you’ve ever tried to stream a PDF file in PHP, you know how incredibly annoying it is to get it working across all browsers. In fact, the maintainer of HtmlToPdf didn’t have an official response on the topic of streaming PDF data to the browser. It only worked most of the time. When it fails, the page loads the data, but nothing actually shows up and your PDF reader will not fire.
The very short explanation is that IE ignores certain content type headers and tries to guess what a file is based on its content. This is a problem in some situations when IE guesses wrong. God, IE is so dumb because it tries to be too smart. Don’t you hate people like that?
Anyway, to get it to work, you have to hack at it. There are added complications to this when you are using HTTPS instead of HTTP.
After we spent a few hours today at work trying to solve this problem, I remembered I had done this before. I dug up some old code and found the solution:
$filename = ‘yourfilename.pdf’;
header(”Pragma: public”);
header(”Expires: 0″);
header(”Cache-Control: must-revalidate, post-check=0, pre-check=0″);
header(”Cache-Control: public”);
header(”Content-Description: File Transfer”);
header(”Content-Type: application/pdf”);
header(”Content-Disposition: attachment; filename=$filename”);
header(”Content-Transfer-Encoding: binary”);
// echo the pdf raw binary data here
As far as I know, this works in every browser. All you Googlers: Enjoy!
Leave a comment if this worked!









tnx, simple and useful
Comment by giorgio salluzzo — July 31, 2007 @ 2:48 am
thx very much
Comment by great — October 13, 2008 @ 11:38 am
Doesn’t work in FFox
Comment by Nork — November 20, 2008 @ 1:27 pm