Your Location is: Home > Cakephp

CakePHP: How to use a view element inside of a controller and get html for genrate pdf using cakephp version 2.4.5

From: Luxembourg View: 2522 Surender Kumar 

Question

I am trying to get HTML from view in CakePHP and want to use it in controller to generate PDF, but when I send HTML in variable I get an error, but it's working for texts. I am calling function like this :

<?php

    $dataforpdf = '<h1>this is test text</h1>';


    echo $this->Html->link('Downloads PDF',  
        array('controller' =>'employers','action'=>'generatePDF',$dataforpdf )
     ); 
?>

My CakePHP version 2.4.5 and my controller function:-

public function generatePDF($id = null)
{    
    $dataforpdf  = $id;

    require('mpdf/mpdf.php');

    $mpdf=new mPDF();
    $mpdf->WriteHTML($strContent);
    $mpdf->Output('Pdf Report.pdf','D');die;
 }

Best answer

You're approaching this in a very backwards way. Your Controller should be preparing the data for a View; whereas in your code you are preparing the data in the View to pass to the Controller.

Passing HTML in the route is really not a good idea. It would be better to generate the HTML using a View template from within your controller action:-

public function generatePDF($id = null)
    $View = new View($this, false);
    $View->set(compact('some', 'vars'));
    $html = $View->render('view_name', 'layout_name');

    require 'mpdf/mpdf.php';
    $mpdf = new mPDF();
    $mpdf->WriteHTML($html);
    $mpdf->Output('Pdf Report.pdf','D');
    die;
}

Here view_name.ctp would be a template containing the HTML you require for your PDF.

I'd recommend taking a look at this article on Generating PDFs with CakePHP. There also appears to be a CakePHP 2.x plugin for the PDF library you are using which you should consider using.