Jelle De Loecker
Jelle De Loecker

Reputation: 21955

Render view to variable in CakePHP 1.3 (to generate pdf and download file)

I'm trying to render a view to a variable. This variable will then be used to generate a pdf. Then that pdf should be downloaded with the Media view.

Here's my controller code:



        $dir = ROOT . '/app/tmp/evaluationpdf/';
        $path = $dir . $evaluationid . '.pdf';

        $evaluation = $this->SelfEvaluation->find('first', array(
            'conditions' => array('SelfEvaluation.id' => $evaluationid),
            'contain' => array('Submission' => array('Application'), 'Applicant', 'Member')));

        $this->set(compact('evaluation'));
        $this->output = '';
        $this->layout = false;
        $html = $this->render('/elements/self_evaluation_pdf');

        $this->_generate_pdf($html, $path);

        $this->view = 'Media';

        $params = array(
                'id' => $evaluationid . '.pdf',
                'name' => $evaluationid,
                'download' => true,
                'extension' => 'pdf',
                'path' => $dir,
        );

        $this->set($params);

The file is created as it should, but the first '$this->render' output is also sent to the browser.

The file is never downloaded.

Any idea on how to fix this?

Upvotes: 3

Views: 2736

Answers (3)

Derek
Derek

Reputation: 4751

The simple fix is to just set $this->output to '' after your first render() call.

The more correct way is to use requestAction() instead of render().

Upvotes: 1

Vineet
Vineet

Reputation: 287

You just have to write the code below in self_evaluation_pdf.ctp

  header("Content-Disposition: attachment; filename='downloaded.pdf'");
  header('Content-type: application/pdf');

The dynamic content in this view will be downloaded as a PDF file on the client side.

Upvotes: 0

Matt
Matt

Reputation: 1358

In CakePHP 2.x I did the following in order to use a view to generate a barcode label format:

      $response = $this->render('/Labels/' . $printer['Printer']['model'] . '/manifest', 'ajax');
      $body = $response->body();
      $response->body('');

Which gave me the view data as $body. Then I could just redirect or if the request was ajax just set autoRender to false and return ''.

It kind of muddies the MVC waters but it is simple.

Upvotes: 0

Related Questions