RuSs
RuSs

Reputation: 789

django reportlab attach pdf to email, save pdf to server, show pdf in browser

There are 3 questions I have about a generated pdf using report lab in django which I can't seem to find a good answer for. The documentation on the django site only covers how to generate a pdf for download. But how do I attach the generated pdf to an email and send it instead of downloading it? How do I save the pdf to a directory on the server instead of downloading it? How do I display the pdf in the browser window instead of downloading it? Just use the django documentation example:

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

Upvotes: 2

Views: 3538

Answers (2)

Carla Urrea Stabile
Carla Urrea Stabile

Reputation: 869

To display de PDF on your browser instead of downloading it you just have to remove the word attachment from

response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

you would have something like this

response['Content-Disposition'] = 'filename="somefilename.pdf"'

Upvotes: 5

You can pass a regular filename to Canvas() instead of a file-like object. You should generally pass in as the next parameter the pagesize - default is A4.

For all the details, download the user's guide & reference guide from ReportLab:

http://www.reportlab.com/docs/reportlab-userguide.pdf

See page 10.

Upvotes: 1

Related Questions