Code snippets are bits of re-usable code submitted by the ReportLab community. We don't promise that they are accurate, up-to-date or correct - use them at your own risk!
We'd love it if you could participate by submitting your own snippets and sharing your experience with others by commenting. You will need to create a user account by filling out our very simple form.
View all snippets
Creating a PDF in memory from within a web application
Example Django web application view which generates a PDF in memory and returns it as the result of an HTTP request. This example uses RML as the document source.
RML2PDF is a central component of ReportLab PLUS: a translator which converts high level XML markup into PDF documents. Report Markup Language describes the precise layout of a printed document, and RML2PDF converts this to a finished document in one step.
See the RML User Guide for more information about RML.
from django.http import HttpResponse from rlextra.rml2pdf import rml2pdf import cStringIO def getPDF(request): """Returns PDF as a binary stream.""" # Use your favourite templating language here to create the RML string. # The generated document might depend on the web request parameters, # database lookups and so on - we'll leave that up to you. rml = getRML(request) buf = cStringIO.StringIO() rml2pdf.go(rml, outputFileName=buf) buf.reset() pdfData = buf.read() response = HttpResponse(mimetype='application/pdf') response.write(pdfData) response['Content-Disposition'] = 'attachment; filename=output.pdf' return response