Search code examples
phpdompdf

Pass data to dompdf (not with Laravel)


I have seen a lot of answers using Laravel but I am not using a framework and want to pass some data. Is it possible? I tried passing $data as a second argument to loadHtml but that does not work.

        $options = new Options();
        $options->set('defaultFont', 'Arial');
        $dompdf = new Dompdf($options);

        $data = ['test' => 'here is the data I want to pass'];
    
        ob_start();
        require("mypath/templates/pdf-file.php");
        $html = ob_get_contents();
        ob_get_clean();
    
        
        $dompdf->loadHtml($html);
    
        $dompdf->setPaper('A4', 'portrait');
        
        $dompdf->set_option('isHtml5ParserEnabled', true);
        $dompdf->set_option('isRemoteEnabled', true);

        $dompdf->render();

        $dompdf->stream();

Solution

  • Variables defined before a require or include are accessible in the required/included file. This means if pdf-file.php is the file which generates the HTML, you can just use the variable $data inside pdf-file.php to fill the (dynamic) information required to build the PDF