Generating pdf custom report from API models and sending email as an attachment

Hi ALL

I am wondering if you could help on adding views function to Django REST API such that when the URL is hit, pdf is rendered that contains customized models attributes of specific instances

In my current project i am building flight booking backend system. Here is a views function using reportLab library

@api_view()
def flight_pdf(request):
response = HttpResponse(content_type=‘application/pdf’)
d = datetime.today().strftime(‘%Y-%m-%d’)

buf = io.BytesIO()
c = canvas.Canvas(buf, pagesize=letter, bottomup=0)
textob = c.beginText()
textob.setTextOrigin(inch, inch)
textob.setFont('Helvetica', 14)

queryset = Booking.objects.all()
lines =[]

for booking in queryset:
    lines.append(booking.ticket_number)
    lines.append(booking.confirmation_number)
    lines.append(booking.price)
    lines.append(booking.issue_date)
    lines.append(booking.passenger)
    lines.append(booking.flight)
    lines.append("")

for line in lines:
    textob.textLine(str(line))

c.setTitle(f"...Generated on {d}...")
c.drawText(textob)
c.showPage()
c.save()
buf.seek(0)

return FileResponse(buf, as_attachment=True, filename='flight.pdf')

In this project i want the pdf API to render flight booking page for a particular passenger and then mount on React JS button

Any idea or help will be highly appreciated

You mentioned React. Are you wanting to do something like this (display a PDF in a React app)?

React is ok. i am now working the Django backend to generate pdf from the models for each instance.

I tried reportLab library but i noticed resources on the internet are not enoug

I now succeeded in rendering the views function into html. I now have beautiful ticket html url page where all the attributes i needed are rendered

The only thing remaining now is redering the html into pdf. and then passing it to the email backend as an attachment
that pdf URL is what i want to mount to the react JS as a button (i can handle this part)

Have you tried something like pdfkit?