I have a page where several buttons process different functions like sending a user sms (via API), sends an file by email, or downloads a PDF file. Button actions dont use forms, but uses ajax requests via javascript.
I used to create a pdf file using javascript (jspdf), but have written code which generates a pdf file by python on the server. Now I need to allow download when the button is clicked.
Server code snippet:
with NamedTemporaryFile(mode='w+b') as temp:
from django.http import FileResponse
doc = SimpleDocTemplate(
temp.name, pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=20, allowSplitting=1, title="Prescription", author="MyOPIP.com")
doc.build(elements)
return FileResponse(open(
temp.name, 'rb'), content_type='application/pdf')
The above code is supposed to download a pdf file, if called ny navigating to the url.
On my javascript side, I tried to determine what I'm receiving:
$.ajax({
url: `/clinic/${cliniclabel}/prescription/download/patient/${patient_id}`,
dataType: "html",
data: data,
type: 'POST',
success: function (data) {
console.log("Received data from server..type is ", typeof(data))
console.log(data)
}
});
And I get:
Received data from server..type is string
userjs/main.js:2067 %PDF-1.4
1 0 obj
<<
/F1 2 0 R /F2 5 0 R
>>
endobj
2 0 obj....
Apparently django sends this as a file stream. How can I get the file downloaded to the user when the response is processed by javascript?
Sincerely yours,
Dr Joel G Mathew