0

I tried the converting to blob but it says error in opening the file.

 var a = document.createElement("a");
 document.body.appendChild(a);
 a.href = 'data:application/octet-stream;base64,' + fileData;
 a.download = 'fileName.pdf';
 a.click();

The above code is working fine but when i tried the code in the below links the solution dint work. can any one please help me where im missing. Because i have spent a day on it.

Failed to load PDF document - Angular JS - BLOB

PDF Blob is not showing content, Angular 2

thanks, priya

priya_21
  • 159
  • 1
  • 2
  • 15
  • 2
    How did it not work? Was there an error? What does it say? – Lazar Ljubenović Aug 01 '18 at 09:01
  • received blob(2100) like this format and file downloaded but while opening the file it says error. and downloaded file size was 1kb. The above code worked but the links i provided above didnot work – priya_21 Aug 01 '18 at 09:13

1 Answers1

0

Extended some more time on it and found the solution. This solution may help some one.

convertbase64toArrayBuffer(base64) {
    var binary_string = window.atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
      bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
  }

conversion should be base64 string to bufferarray then to blob.

Adding some more steps for @sanjay you need to install filesave npm package -> "file-saver": "^1.3.8",

npm install "file-saver": "^1.3.8"

var byteArr = this.convertbase64toArrayBuffer(base64string);
var blob = new Blob([byteArr], { type: 'application/pdf' });
FileSaver.saveAs(blob, "filename" + extension);

Hope this helps

Thank you

priya_21
  • 159
  • 1
  • 2
  • 15