Generate PDF with WeasyPrint having common header/footer and pagination

Solution 1:

Since Weasyprint supports CSS Paged Media Module Level 3, simple headers and footers (e.g. pagination, like you mentioned) can be accomplished using CSS:

@page {
    @top-right{
        content: "Page " counter(page) " of " counter(pages);
    }
}

Make sure you include your stylesheets when rendering:

HTML(string=rendered_html,
     base_url=settings.SITE_URL).write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + '/css/pdf_render.css')])

However, getting more complex headers/footers to render can be more.. complex. Some people have suggested the method of including a div element in the header that renders only for print (but I must admit I have only been able to get simple elements to render properly with this method):

@page {
    @top-left {
        content: element(pageHeader);
    }
}
@media print {
    #divHeader{
        position: running(pageHeader);
    }
}

There is also another method using fixed positions, as demonstrated in this gist: https://gist.github.com/pikhovkin/5642563

Solution 2:

Currently running elements are not supported by WeasyPrint. Nevertheless I found a way to achieve the same result using named strings:

 @page {
   @top-center {
     content:  string(title);
   }
 }

 header {
   width: 0;
   height: 0;
   visibility: hidden;
   string-set: title content();
}

Now you can add your content to an invisible HTML header element.

<header>Content of the header goes here</header>