1

Django documentation has the following example for ReportLab.

from reportlab.pdfgen import canvas
from django.http import HttpResponse

def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    # Create the PDF object, using the response object as its "file."
    p = canvas.Canvas(response)

    # Draw things on the PDF. Here's where the PDF generation happens.
    # See the ReportLab documentation for the full list of functionality.
    p.drawString(100, 100, "Hello world.")

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()
    return response

However. I want to use RML to generate my PDF. ReportLab Plus offers an rml2pdf function that can turn an RML document into a PDF using a similar markup to Django's templating. How can I provide Django the RML template and have Django return the PDF in the API response, similar to the example in the documentation?

medley56
  • 1,181
  • 1
  • 14
  • 29

1 Answers1

0

Figured it out.

RML Template

Put this in your Django templates folder so Django can find it.

Call it templates/rml_template.rml

<!DOCTYPE document SYSTEM "rml.dtd">
<document filename="example_01.pdf">
 <template>
 <!--this section contains elements of the document -->
 <!--which are FIXED into position. -->
 <pageTemplate id="main">
 <frame id="first" x1="100" y1="400" width="150" height="200"/>
 </pageTemplate>
 </template>
 <stylesheet>
 <!--this section contains the STYLE information for -->
 <!--the document, but there isn't any yet. The tags still -->
 <!--have to be present, however, or the document won't compile.-->
 </stylesheet>
 <story>
 <!--this section contains the FLOWABLE elements of the -->
 <!--document. These elements will fill up the frames -->
 <!--defined in the <template> section above. -->
 <para>
 Welcome to RML!
 </para>
 <para>
 This is the "story". This is the part of the RML document where
 your text is placed.
 </para>
 <para>
 It should be enclosed in "para" and "/para" tags to turn it into
 paragraphs.
 </para>
 </story>
</document>

Django View

This view loads the template as a string and rml2pdf uses the response object as its "file" to write to, similar to the Django documentation example.

from django.template import loader
from rlextra.rml2pdf import rml2pdf
from django.http import HttpResponse


def some_view(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    context = {} # You can add values to be inserted into the template here

    rml = str(loader.render_to_string('rml_template.rml', context))
    rml2pdf.go(rml, outputFileName=response)

    return response
medley56
  • 1,181
  • 1
  • 14
  • 29