I am trying to transfer the processed pdf file on the server to the client side so that the user can download it.
Here is my code on the server –
@app.task
def pdf_protect(file_path, file_id, password):
with open(file_path, 'rb') as file:
reader = PdfReader(BytesIO(file.read()))
writer = PdfWriter()
writer.append_pages_from_reader(reader)
writer.encrypt(password)
output = io.BytesIO()
writer.write(output)
output.seek(0)
send_notification.delay({'filename': 'result.pdf', 'content': base64.b64encode(output.read()).decode('utf-8')}, file_id)
In this code I use the pypdf library and encrypt the pdf with the given password.
After that, I try to convert the processed pdf file into bytes and pack it into json in order to send it to the client side via a websocket connection.
On the client side I have the following code –
chatSocket.onmessage = function (e) {
const data = JSON.parse(e.data);
var blob = new Blob([data.message.content], {type: "application/pdf"});
console.log(data.message.content)
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = data.message.filename;
chatSocket.close();
};
In this code I get the data from the json and make a link to download the file.
But after downloading and opening the pdf file, the error “Failed to load the PDF document.” or just a blank page.
But what happens when I send a response to the client via FileResponse and then use the same method to make a link to download the file and download it, then everything works fine.
This is what this code looks like −
protected_pdf_file = services.pdf_protect(form.cleaned_data['file'], form.cleaned_data['password'])
return FileResponse(
protected_pdf_file,
as_attachment=True,
filename='protected_pdf.pdf',
)
And here is the code services.protect_pdf() –
def pdf_protect(pdf_file, password):
reader = PdfReader(pdf_file)
writer = PdfWriter()
writer.append_pages_from_reader(reader)
writer.encrypt(password)
output = io.BytesIO()
writer.write(output)
output.seek(0)
return output
Please tell me what the problem is and how to transfer files from the client to the server via json.
Thank you!