Manage to download PDF stream with Blob in javascript
Asked Answered
H

1

6

A web page (front) is calling a service which send a PDF stream as a response : Here is the front code :

'click .btn': function (event) {
   /.../
   event.preventDefault();
   Http.call(params, (err, res) => { // callback
     if (err) console.log(err); // nothing
     console.log({ res }); // print below result
     const blob = new Blob(
       [res.content],
       { type: `${res.headers['content-type']};base64` }
     );
     saveAs(blob, res.headers['content-disposition'].slice(21));
   });
 }

Here is the response from the server ( console.log(res) ) : { res : Object } printed in the console.

content: "%PDF-1.4↵1 0 obj↵<<↵/Title (��)↵/Creator (��)↵/Prod ..... lot of characters....%"
data: null,
statusCode: 200,
headers: {
  connection: "close",
  content-disposition: "attachment; filename=myDoc.pdf"
  content-type: "application/pdf",
  date: "date",
  transfer-encoding: "chunked",
  x-powered-by: "Express"
}

However, the PDF is downloaded with no content, it's full blank like corrupted ( But I can see the content in the string ). It works well with the CSV routes ( I send a csv as a stream and download it with the same method and I got the data).

I think there is something with the format %PDF ...% but I didn't manage to find something. Note : With postman, it works, my PDF is saved, the page is not blank, I got the data. So there is something in the front I am not doing right. I also tried with :

  const fileURL = URL.createObjectURL(blob);
  window.open(fileURL); // instead of saveAs

but the result is the same ( but in another tab instead of saved PDF ) blank page. Any ideas ?

Hygrometry answered 8/2, 2017 at 9:39 Comment(3)
For more details, here is the complete PDF string : edit : I cannot past it here, it is too long...Hygrometry
You could use pastebin.com for the pdf content, but try changing the content-type to "application/octet-stream".Chivalrous
No I had to find an other solution. The backend upload the PDF to AWS S3, then I send a link to download this PDF. And then the front download the PDFHygrometry
C
0

You probably forgot to specify the response type in your inital backend call - from the example you posted "arraybuffer" would be the correct one here, you can check all types here.

Catchpenny answered 23/1, 2023 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.