Last active
February 24, 2019 01:02
-
-
Save squarepegsys/e9b7426af65cf5f1b94312beaca7d56d to your computer and use it in GitHub Desktop.
Dynamic Header in ReportLab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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