March 28, 2007

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! :)

Filed under: PHP — Michi @ 11:57 pm

Share this

These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Reddit
  • StumbleUpon
  • del.icio.us
  • description
  • Technorati
  • Slashdot
  • co.mments
  • NewsVine

Related

I predicted that YouTube would eventually stream something live (or very close to live). This most readily applies to events that are long. This is important because "sponsored" content could be longer than their current 10 minute cap. It is...
I have been bad about updating, and this goes back to an old habit that probably has to do with human nature: as time between updates increases, there's a desire to write a "big" update, which is increasingly difficult as...

3 Comments »

TrackBack URI | Blog RSS | Comment RSS

  1. tnx, simple and useful :)

    Comment by giorgio salluzzo — July 31, 2007 @ 2:48 am

  2. thx very much

    Comment by great — October 13, 2008 @ 11:38 am

  3. Doesn’t work in FFox

    Comment by Nork — November 20, 2008 @ 1:27 pm

What do you think?