Django Reportlab Examples

It's been far too long since my last post.  A lot has happened and the holidays make things so busy but I'm back and ready to get back in to the swing of things.  To start off the new year I'm going to do a series of posts relating to ReportLab specifically with its application to Django.  I want to go over a few of the pitfalls I've experienced and how to get things set up.  ReportLab is notoriously tricky to get working and the documentation seems sparse to say the least.  I hope these posts help not only myself remeber how I did all of this but others who are struggling with the same problems.ReportLab The problem is simple, how to generate PDFs using Django.  In our on going rewrite of our system at work we are getting to PDF generation.  The old system uses wkhtmltopdf which is great if you just want something to render HTML out to a PDF and you don't give much care to speed or formatting.  Wkhtmltopdf suffers from having to use HTML to format everything on the page.  This is l...

Last time we looked at how to generate a very simple PDF using ReportLab and Django, ReportLab and Django – Part 1 – The Set Up and a Basic Example.  This time let's make the PDF a little bit more interesting with some headers and footers.  ReportLab gives a pretty good amount of control when it comes to adding headers and footers to your PDF.  To start off let's bring back the simple __init__ method we had from last time and add a header/footer method to it.from reportlab.lib.pagesizes import letter, A4 from reportlab.lib.styles import getSampleStyleSheet class MyPrint: def __init__(self, buffer, pagesize): self.buffer = buffer if pagesize == 'A4': self.pagesize = A4 elif pagesize == 'Letter': self.pagesize = letter self.width, self.height = self.pagesize @staticmethod def _header_footer(canvas, doc): # Save the state of our canvas so we can draw on it canvas.saveState() styles = getSample...