0

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 usef = open('result.pdf', 'wb') and f.write(str) 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: (saveAs function is in FileSaver.js, 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?

mort
  • 12,988
  • 14
  • 52
  • 97
Mr.ChenZ
  • 147
  • 1
  • 3
  • 12

1 Answers1

0

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: http://jsfiddle.net/mowglisanu/15h9o3d5/

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

Community
  • 1
  • 1
jdgregson
  • 1,457
  • 17
  • 39
  • really thanks!!! It's my fault, I made a stupid mistake...When web get the server data, it should use `var str = "{{ data }}"`, but I use `var str = {{ data }}`...T_T – Mr.ChenZ Apr 29 '16 at 02:20