Search code examples
phpcakephppdf-generationcakephp-3.0dompdf

How to load html file inside cakephp using dompdf


I am using dompdf with cakephp 3.6 to generate prints from HTML to PDF

I have a function name test inside drivercontroller and i want to load a ctp file which is created inside src\Template\DriverDetails and filename is testpdf.ctp

Can u plz help me to suggest how to pass complete file.

Below is my code

public function test()  {
            $html = file_get_contents("testpdf.ctp");            
            $dompdf = new Dompdf();
            $dompdf->loadHtml($html);
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream("invoice.pdf", array("Attachment" =>0));
            exit(0);
        }

src\Template\DriverDetails\testpdf.ctp

<html>
    <body>
        <table>
            <tr><td align="center"><?php echo $id; ?></td></tr>
            <tr><td align="center">Demo Data</td></tr>
        </table>
    </body>
</html>

Solution

  • You can try like that way.

    public function test()
    {
        $data = "This can be accessible in view file";
        $builder = $this->viewBuilder();
        $builder->autoLayout(false);
    
        // set your template path [don't use .ctp]
        $builder->template('Users/add');
    
        //Pass data into view file
        $view = $builder->build(['data' => $data]);
    
        //Render view file content and store into variable
        $viewContent = $view->render();
        var_dump($viewContent);
    }