Showing posts with label PDF Header. Show all posts
Showing posts with label PDF Header. Show all posts

Monday, May 15, 2017

How to add header/footer to multipage pdf on Laravel SnappyPDF WkHtmlToPdf

I am sure you already install WkhtmlToPDF with Snappy in your Laravel project. If not yet please visit the link below to install WkhtmltoPDF in your Laravel project:

Click here.

Now add margin for your page if not added yet because header and footer need some space to visible in PDF header and footer area by editing the file named "config/snappy.php".

<?php
return array(
    'pdf' => array(
        'enabled' => true,
        'binary'  => 'C:\PROGRA~1\wkhtmltopdf\bin\wkhtmltopdf.exe',
        'timeout' => false,
        'options' => array(
            'margin-top'    => 15,
            'margin-right'  => 8,
            'margin-bottom' => 20,
            'margin-left'   => 5
        ),
        'env'     => array(),
    ),
    'image' => array(
        'enabled' => true,
        'binary'  => 'C:\PROGRA~1\wkhtmltopdf\bin\wkhtmltoimage.exe',
        'timeout' => false,
        'options' => array(),
        'env'     => array(),
    )

);


And then append header and footer html in your PDF as follows:

$header_html = file_get_contents(resource_path() . "/" . "pdf-header.html");
$footer_html = file_get_contents(resource_path() . "/" . "pdf-footer.html");

$pdf = SnappyPDF::loadView('home.pdf');
$pdf->setOption('header-html', $header_html);
$pdf->setOption('footer-html', $footer_html);

return $pdf->stream('invoice.pdf');

You have to create two file named "pdf-header.html" and "pdf-footer.html" in your "resource" folder as below.

pdf-header.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body style="border: 1px solid blue;margin-left: 18px;margin-right: 0px;padding:10px">
<div style="color: red">
    THIS IS <b>PAGE HEADER</b>
</div>
</body>

</html>

pdf-footer.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body style="border: 1px solid blue;margin-left: 18px;margin-right: 0px;padding:10px">
<div style="color: red">
    THIS IS <b>PAGE FOOTER</b>
    Page=<span id="page"></span>|
    Total Page=<span id="topage"></span>|
    Date=<span id="date"></span>|
    Time=<span id="time"></span>
</div>
<script type="text/javascript">
    var vars={};
    var x=window.location.search.substring(1).split('&');
    for (var i in x) {
        var z=x[i].split('=',2);
        vars[z[0]] = unescape(z[1]);
    }
    document.getElementById('page').innerHTML = vars.page;
    document.getElementById('topage').innerHTML = vars.topage;
    document.getElementById('date').innerHTML = vars.date;
    document.getElementById('time').innerHTML = vars.time;
</script>
</body>

</html>




PDF will look like below images: