Mr.ChenZ Mr.ChenZ - 9 months ago 81
Javascript Question

How to download pdf on web

Important: I use python.

I use reportlab to create a pdf on the server (flask), and I get a string by methond

str = canvas.getpdfdata()
. I can use
f = open('result.pdf', 'wb')
to save this as pdf.

Now I want to download this pdf on web, but I don't want to create a pdf file on the server, so I send the string to web, and want to use js to the create file and download it.

I tried to use js code like this: (
function is in
, which can be found on github)

var blob = new Blob([{{ str }}], {type: "application/pdf"});
saveAs(blob, "result.pdf");

It throws the error
Uncaught SyntaxError: Unexpected identifier
, I try to change the string encoding to hex and base64, but it does not help.

Can you help me? Or can you tell me a way to create and download this pdf without creating a file on the server?


As read in the answer to this SO question, you need to convert the binary data to an ByteArray first:

var byteArray = new Uint8Array(hexdata.length/2);
for (var x = 0; x < byteArray.length; x++){
    byteArray[x] = parseInt(hexdata.substr(x*2,2), 16);
var blob = new Blob([byteArray], {type: "application/octet-stream"});

Example here:

And this question is asking the exact same thing as you.