Speed up development with full-stack environments for every branch.

Learn More

Generate PDF [Python and Django]

Forked from Hello World in Django.

2386 Runs 7230 Views 1377 Copies
Saved

Saved

bhawani0915 49

bhawani0915
published 3 years ago

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

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

    temp = StringIO()

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

    # 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.
    p.showPage()
    p.save()

    # Get the value of the StringIO buffer and write it to the response.
    response.write(temp.getvalue())
    return response
Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).