Outputting PDFs with Django

Install ReportLab

The ReportLab library is available on PyPI. A user guide (not coincidentally, a PDF file) is also available for download. You can install ReportLab with pip:

python -m pip install reportlab

Write your view

The key to generating PDFs dynamically with Django is that the ReportLab API acts on file-like objects and Django’s FileResponse objects accept file-like objects.

Here’s a “Hello Real Programmer” example:

// views.py

from reportlab.pdfgen import canvas  
from django.http import HttpResponse  
  
def getpdf(request):  
    response = HttpResponse(content_type='application/pdf')  
    response['Content-Disposition'] = 'attachment; filename="download.pdf"'  
    p = canvas.Canvas(response)  
    p.setFont("Times-Roman", 55)  
    p.drawString(200,800, "Hello, Real Programmer”.")  
    p.showPage()  
    p.save()  
    return response  
Leave a Comment