Save datastream received as unit8array as pdf to filesystem on the front end

1.6k Views Asked by At
const reader = response.body.getReader();
        reader.read()
            .then(({ done, value }) => {
                var link = document.createElement("a");
                value = window.btoa(value) //<-tried with and without
                link.download = "test.pdf";
                link.href = 'data:application/pdf;base64,'+value
                link.click();
                // console.log(window.atob(value))
            })

this just saves a pdf file which has nothing in it / is unreadable.

value in the callback is unicode for a pdf file read into a data stram so its just a bunch of numbers in a unit8array. I tried converting it to base64 and downloading that through a data uri but haven't had any luck.

This is in an electron application btw

edit:

When I receive the data from the backend, the request shows it as unicode, but the response gives it to me as a readable stream. I am 100% sure I would be able to parse the unicode and save a PDF file from it but I do not know how to get the unicode form from the given readable stream.

1

There are 1 best solutions below

8
On

Try giving the file a name:

link.name = "file.pdf";

and then using the base64 to make a data URI. If that doesn't work, try making your data URI like this:

'data:application/octet-stream;charset=utf-16le;base64,' + value;

It might be worthwhile to debug the dataURI if possible, the data you're getting could be corrupted to begin with which will have you chasing your tail.

You could also try converting the Uint8Array to a File object:

var arr = [];
var arr.push(value);
var pdf = new File(arr, 'test.pdf', {type: 'application/pdf'});

And then attach that to a FormData object and post it to your server. Edit* oops didn't see you were doing this with electron so I'm not sure if the above applies but it may still be helpful. Best of luck!