I'm using React and Graphql on the frontend and Django and Graphene on the backend.
I want to be able to download a pdf file of a report. I try to do it using mutation as follows:
const [createPdf, {loading: createPdfLoading, error: createPdfError}] = useMutation(CREATE_PDF)
const handleCreatePDF = async (reportId) => {
const res = await createPdf({variables: {reportId: parseInt(reportId) }})
debugger;
};
export const CREATE_PDF = gql`
mutation ($reportId: Int!) {
createPdf (reportId: $reportId){
reportId
}
}
`;
On the backend I have something like this:
class CreatePDFFromReport(graphene.Mutation):
report_id = graphene.Int()
class Arguments:
report_id = graphene.Int(required=True)
def mutate(self, info, report_id):
user = info.context.user
if user.is_anonymous:
raise GraphQLError("You are not logged in!")
report = Report.objects.get(id=report_id)
if not report:
raise GraphQLError("Report not found!")
if user != report.posted_by:
raise GraphQLError("You are not permitted to do that!")
html_string = render_to_string('report.html', {'report_id': 1})
pdf_file = HTML(string=html_string)
response = HttpResponse(pdf_file, content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="rapport_{}"'.format(report_id)
return response
# return CreatePDFFromReport(report_id=report_id)
When I uncomment return CreatePDFFromReport(report_id=report_id)
it works fine.
But I want to return pdf file.
Is there any possibility to do that?
Thanks.