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');
}