Search

10 May, 2019

Django: Creating PDF , writing content and returning as a downloaded file

Hi guys,

It took me hours to make it finally work but working with PDFs is a pain. I want to share what worked for me.

The canvas should be thought of as a sheet of white paper with points on the sheet identified using Cartesian (X,Y) coordinates which by default have the (0,0) origin point at the lower left corner of the page.


from reportlab.pdfgen import canvas
import io

pdf_buffer = io.BytesIO()
p = canvas.Canvas(pdf_buffer)
p.drawString(0, 100, "Hello People")
p.showPage()
p.save()

response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="some_file.pdf"'
pdf_value = pdf_buffer.getvalue()
response.write(pdf_value)
return response

Above code , generates a pdf with the words "Hello People" written in it. 

No comments:

Post a Comment