pdfkit headers and footers

user3368835 picture user3368835 · Dec 14, 2015 · Viewed 10.8k times · Source

I've been searching the web for examples of people using the pdfkit (python wrapper) in implementing headers and footers and could not find any examples.
Would anyone be able to show some examples of how to implement the options in wkhtmltopdf using the pdfkit python wrapper?

Answer

VStoykov picture VStoykov · Jan 12, 2016

I'm using it only with headers but I think that it will work the same with footers.

You need to have separate html file for the header.

header.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>

    Code of your header goes here.

</body>
</html>

Then you can use it like that in Python

import pdfkit

pdfkit.from_file('path/to/your/file.html', 'out.pdf', {
    '--header-html': 'path/to/header.html'
})

The tricky part if you use some backend like Django and want to use templates is that you can't pass the header html as rendered string. You need to have a file.

This is what I do to render PDFs with Django.

import os
import tempfile
import pdfkit

from django.template.loader import render_to_string


def render_pdf(template, context, output, header_template=None):
    """
    Simple function for easy printing of pdfs from django templates

    Header template can also be set
    """
    html = render_to_string(template, context)
    options = {
        '--load-error-handling': 'skip',
    }
    try:
        if header_template:
            with tempfile.NamedTemporaryFile(suffix='.html', delete=False) as header_html:
                options['header-html'] = header_html.name
                header_html.write(render_to_string(header_template, context).encode('utf-8'))

        return pdfkit.from_string(html, output, options=options)
    finally:
        # Ensure temporary file is deleted after finishing work
        if header_template:
            os.remove(options['header-html'])

In my example I create temporary file where I put rendered content. Important part is that temporary file need to end with .html and to be deleted manually.