0

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.

Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46

1 Answers1

1

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;
  }
}
Dipak Telangre
  • 1,792
  • 4
  • 19
  • 46
  • Thanks for posting the solution to this issue. I suggest you try to mark your own answer to this question after 48 hrs when it is available to mark. It can help other community members in the future in similar kinds of issues. Thanks for your understanding. – Deepak-MSFT May 08 '20 at 14:57