Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamic Header in ReportLab
from functools import partial
# lots of other imports, esp for reportlab
# this function is ran for each page.
def some_header(canvas,doc,content):
canvas.saveState()
P = Paragraph(content,style=some_style)
w, h = P.wrap(doc.width, doc.topMargin)
P.drawOn(canvas, doc.leftMargin, doc.height+doc.topMargin-h)
canvas.restoreState()
# our dyanmic content
our_content = "Today is {}".format(datetime.now())
buf = io.BytesIO()
doc = SimpleDocTemplate(buf,
pagesize=letter,
leftMargin=0.25*inch,
rightMargin=0.75*inch,
topMargin=1.5*inch, # make sure you have room for the header!
bottomMargin=0.25*inch,
)
# here is where the currying happens.
# I can set a function as a variable because Python is awesome like that.
header = partial(some_header, content=our_header)
# note that we have to specify it on the first and the rest of the pages.
doc.build(self.doc_elements,
canvasmaker=canvas_class,
onFirstPage=header,
onLaterPages=header
)
buf.seek(0)
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.