Как правильно использовать xhtml2pdf для инициирования загрузки pdf в django rest framework
У меня есть приложение, для которого я использую django rest framework для бэкенда и react для фронтенда. У меня есть кнопка загрузки во фронтенде, которая делает api вызов к представлению, которое управляет генерацией pdf. Я просмотрел учебник на youtube, но не смог понять, как реализовать этот метод в django rest framework. Пожалуйста, подскажите, как я должен изменить приведенный ниже код, чтобы он работал с react front end для запуска загрузки при вызове api.
utils.py
def render_to_pdf(template_src, context_dict={}):
print(context_dict)
template = get_template(template_src)
html = template.render(context_dict)
result = BytesIO()
pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return None
views.py
@api_view(['GET'])
# @permission_classes([IsAuthenticated])
def download_citation_as_pdf(request, pk):
try:
query = Civil.objects.get(id=pk)
serial = Full_Detail_Serial(query, many = False)
pdf = render_to_pdf('citationPdfEmail.html', serial.data)
# return HttpResponse(pdf, content_type='application/pdf', status = status.HTTP_200_OK)
if pdf:
response = HttpResponse(pdf, content_type = 'application/pdf')
filename = f"{serial.data['title']}_%s.pdf"
content = "inline; filename='%s'" %(filename)
response['Content-Disposition'] = content
return response
return Response({"message": serial.data}, status= status.HTTP_200_OK)
except Civil.DoesNotExist:
return Response({"error": "citation does not exist"}, status= status.HTTP_400_BAD_REQUEST)
except Exception as e:
print(e)
return Response({"error": str(e)}, status= status.HTTP_500_INTERNAL_SERVER_ERROR)
urls.py
urlpatterns=[
path('download-pdf/<str:pk>/', views.download_citation_as_pdf, name='download-pdf'),
]