Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MaxMorais/5783051 to your computer and use it in GitHub Desktop.
Save MaxMorais/5783051 to your computer and use it in GitHub Desktop.
# coding: utf-8
from weasyprint import HTML, CSS
from weasyprint.document import _prepare
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;}')])
page = header.pages[0]
exists_links = exists_links or page.links
header_body = get_page_body(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;}')])
page = footer.pages[0]
exists_links = exists_links or page.links
footer_body = get_page_body(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())
if page_body:
page_body.children += header_body.all_children()
page_body.children += footer_body.all_children()
if exists_links:
_prepare(page._page_box, page.bookmarks, page.links, page.anchors, None)
main_doc.write_pdf(target='main_doc.pdf')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment