Search code examples
phphtmlwkhtmltopdf

wkhtmltopdf passing variable in html file


I use wkhtmltopdf with php, and it works well. Now, i want to add some variables from the php file to the html one, but i don't find a solution.

the PHP file:

<?php
    require '/path/vendor/autoload.php';
    use mikehaertl\wkhtmlto\Pdf;
    $pdf = new Pdf(array(
        'no-outline',
        'margin-top'    => 0,
        'margin-right'  => 0,
        'margin-bottom' => 0,
        'margin-left'   => 0,

        // Default page options
        'disable-smart-shrinking',
));
if($_GET['file'] == 'public'){
    $pdf = new Pdf('template_public.html');
}else{
    $pdf = new Pdf('template_pro.html');
}
    $pdf->send();
?>

The HTML file:

<html>
    <head>
        <title>Generated PDF file</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
        <div>
            {title}
        </div>
    </body>
</html>

How can i replace the {title} in the HTML file?


Solution

  • This should replace all of the {variables} in the html files with their values, given an array of parameters.

    $params = ["title"=>"title_val", "content" => "something", "key" => "value"];
    $pdf = new Pdf();
    $html = file_get_contents($templateFile);    
    foreach($params as $key=>$value) {
        $html = str_replace("{".$key."}", $value, $html);
    }
    
    //Renders the pdf directly from the html string, instead of loading the file directly
    $pdf->addPage($html);
    $pdf->send();