Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Repeat on each page of complex headers (eg, tables) except the first page
# coding: utf-8
from weasyprint import HTML, CSS
def get_page_body(boxes):
for box in boxes:
if box.element_tag == 'body':
return box
return get_page_body(box.all_children())
# Main template
html = HTML('template.html')
main_doc = html.render(stylesheets=[CSS('styles.css')])
exists_links = False
# Template of header
html = HTML('header.html')
header = html.render(stylesheets=[CSS(string='div {position: fixed; top: 1cm; left: 1cm;}')])
header_page = header.pages[0]
exists_links = exists_links or header_page.links
header_body = get_page_body(header_page._page_box.all_children())
header_body = header_body.copy_with_children(header_body.all_children())
# Template of footer
html = HTML('footer.html')
footer = html.render(stylesheets=[CSS(string='div {position: fixed; bottom: 1cm; left: 1cm;}')])
footer_page = footer.pages[0]
exists_links = exists_links or footer_page.links
footer_body = get_page_body(footer_page._page_box.all_children())
footer_body = footer_body.copy_with_children(footer_body.all_children())
# Insert header and footer in main doc
for i, page in enumerate(main_doc.pages):
if not i:
continue
page_body = get_page_body(page._page_box.all_children())
page_body.children += header_body.all_children()
page_body.children += footer_body.all_children()
if exists_links:
page.links.extend(header_page.links)
page.links.extend(footer_page.links)
main_doc.write_pdf(target='main_doc.pdf')
@jsenecal

This comment has been minimized.

Copy link

jsenecal commented Oct 16, 2015

Thanks for this - you saved me a tremendous amount of time :)

@pikhovkin

This comment has been minimized.

Copy link
Owner Author

pikhovkin commented Oct 19, 2015

Welcome! :)

@mahmoudajawad

This comment has been minimized.

Copy link

mahmoudajawad commented Jan 16, 2018

This gist is our python, pdf creating saviour. Thanks a lot for sharing, @pikhovkin.
For anyone trying it, you might want to change:
header = html.render(stylesheets=[CSS(string='div {position: fixed; top: 1cm; left: 1cm;}')])
to:
header = html.render(stylesheets=[CSS(string='@page {size:A4; margin:0;} div {position: fixed; top: 1cm; left: 1cm;}')])
in order to get the full header space available in your PDF page so that you can add even more complex elements.

@farahat80

This comment has been minimized.

Copy link

farahat80 commented Aug 14, 2018

This is brilliant, you saved me a hug amount of time, thanks 👍

@apm-alberto

This comment has been minimized.

Copy link

apm-alberto commented Jan 30, 2019

Thanks a lot man!!!
Great solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.