Thursday, November 26, 2009

Zend Framework: Returning pdf file from an action controller

Lets assume that we have an action called getpdfAction in a Zend Controller. When we execute the action in a browser (e.g. http:://www.oursite.com/somezfcontroller/getpdf), the Zend Application by default will render view associated with the action and if necessary layout. However, when we want to have a pdf file returned or any other file from the action this behaviour is not needed. So, before we read a pdf for returning, we have to disable view script and layout rendering. This can be done as in the example getpdfAction function below:public function getpdfAction() {

//Disable rendering of view script and layout
$this->_helper->viewRenderer->setNoRender();
$this->_helper->layout->disableLayout();


// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('some_pdf_file.pdf');
}

4 comments:

  1. Anonymous7:46 PM

    since you haven't specified you need to create a pdf on-the-fly or require a user to login in order to download the specified file -- a better approach woould be to use Apache's mod_xsendfile as the file will not need to be read by PHP first to be passed off to the client.

    fore examples see http://tn123.ath.cx/mod_xsendfile/

    ReplyDelete
  2. Anonymous12:33 AM

    Ηеllo there! I knοw this is somewhаt off topіc but I was wondering whіch blog
    platform are уοu using for thіs sitе?

    I'm getting fed up of Wordpress because I've had problems with
    hackers and I'm looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

    My blog ... raspberry ketone

    ReplyDelete
  3. Anonymous6:49 AM

    Appreciatіng the cоmmitmеnt you put into your site anԁ detailed infοrmatiοn you offeг.
    Ӏt's great to come across a blog every once in a while that isn't the ѕame outdаted гehаshed mаteгial.
    Excеllеnt reaԁ! I've saved your site and I'm inсluding youг RSЅ feeԁѕ to my Goοgle account.


    Also vіsіt my web pagе credit card debt settlement

    ReplyDelete
  4. Anonymous6:33 PM

    Good article!
    Very simple and very good!
    Thanks

    H.A.

    ReplyDelete