0

I am using django as my backend and I am using restful api to communicate with react js frontend. I have created a pdf invoice with canvas and I was able to send it via mail system of django. But I also want to show the pdf on web page. So I need to send it to front end via api url. I tried to send it as response but I got the error: Object of type Canvas is not JSON serializable

The code that I wrote to send pdf: return Response(c, status=status.HTTP_200_OK)

c stands for the canvas object which is a pdf

Is there a solution of this? Or how do I send the pdf to the front end. Thank you

1 Answers1

0

I think you can send the static url(eg. 127:.0.0.1:8000/static/yourfile.pdf) for the pdf, which will be rendered by the browser. And you can add a button in your react frontend which will redirect to the pdf url.

pratham
  • 47
  • 4
  • I create pdf's when they call the url. So pdf files are not located inside the project they are created when they are requested. Do you think it would be possible – Onat Kutlu Student Dec 29 '20 at 19:44
  • if you want to create pdf in python, create pdf on the go, you just use pyPDF and save in a static folders of your django app and just give the url for it and delete it afterwards. Else option 2 is to create pdf with javascript, you can send all precomputed data from django in a json response, and than put it into pdf in javascript. i guess there is no way to send a serialize a pdf object as you are trying to do above. you can use this thread to generate pdf with js or there are libraries available in react. https://stackoverflow.com/questions/742271/generating-pdf-files-with-javascript – pratham Dec 29 '20 at 20:01
  • that worked thank you! I have a last minor problem. When I design a pdf and save it as canvas.save() it saves it inside the project folder. How can I address it to static folder. I use"from reportlab.pdfgen import canvas" and when I type canvas_object.save() it saves it into project folder – Onat Kutlu Student Dec 29 '20 at 22:59
  • i guess you just have to overwrite the destination path for generated pdf to url/static/name.pdf, acc to this thread https://stackoverflow.com/questions/32485353/python-reportlab-save-with-canvas-to-specified-location you just have to give the path for desired location. in this case, path would be to the static folder. i recommend you to generate path using os.path. canvas_object.save('./project/..../static/name.pdf',size='letter') – pratham Dec 30 '20 at 20:54