Dipak Telangre
Dipak Telangre

Reputation: 1993

JavaScript Download file from Base64 string not working in IE

Want to save/download Base64 as pdf file using javascript. Below code works in chrome but not in IE. I tried many different ways but not working in internet explorer.

Whats wrong with IE ?

function Base64ToPdf(fileName, base64String) {
    const linkSource = "data:application/pdf;base64," + base64String;
    const downloadLink = document.createElement("a");

    downloadLink.href = linkSource;
    downloadLink.download = fileName;
    downloadLink.click();
  }


// Test 
var string = 'Hello World!';
var encodedString = btoa(string);

Base64ToPdf("test.pdf", encodedString);

I have tried with https://stackoverflow.com/a/48796495/2247677 which also not works in IE.

Upvotes: 0

Views: 3818

Answers (1)

Dipak Telangre
Dipak Telangre

Reputation: 1993

I tried many solutions to download Base64 to PDF but not succeeded for IE. Finally I have decided to convert Base64 to Blob first and its working fine in IE 11 and chrome as well.

Full code looks like TS :

export class FileHelper {
  static Base64ToPdf(fileName: string, base64String: string) {
    if (window.navigator && window.navigator.msSaveBlob) {
      const blob = this.Base64toBlob(base64String);
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const linkSource = "data:application/pdf;base64," + base64String;
      const downloadLink = document.createElement("a");
      downloadLink.href = linkSource;
      downloadLink.download = fileName;
      downloadLink.click();
    }
  }

  static Base64toBlob(
    b64Data: string,
    contentType = "application/pdf",
    sliceSize = 512
  ) {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);

      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }

    const blob = new Blob(byteArrays, { type: contentType });
    return blob;
  }
}

Upvotes: 1

Related Questions