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! 🙂

10 thoughts on “PHP Nuisance: How to Stream PDF Files”

  1. How do I display the pdf stream that I received (in xml response – but i have stripped it down to pure pdf stream – so i need to open it somehow)?

Comments are closed.