Angular, Download PDF From BASE64 String


How to download PDF from base64 string using Angular?

In this tutorial, you’ll learn how to convert base64 string to PDF. Let’s start by creating an Angular project.

ng new angular-download-pdf

Once you have the Angular project created, add a button to the app.component.html file.

  Download PDF

On click of the button let’s define a method to download PDF.

Logic: You can make use of an anchor tag to download the PDF. You need to create an anchor tag element, set the source of the anchor tag as base64 string, and click the anchor tag. It will download PDF.

  downloadPdf(base64String, fileName) {
    const source = `data:application/pdf;base64,${base64String}`;
    const link = document.createElement("a");
    link.href = source;
    link.download = `${fileName}.pdf`
    link.click();
  }
  onClickDownloadPdf(){
    let base64String = "your-base64-string";
    this.downloadPdf(base64String,"sample");
  }

IE 11 Work Around To Download PDF from base64 String

The above code won’t work in IE11. We will make use of the msSaveOrOpenBlob method to save the blob as PDF in IE 11.

Logic: First you’ll decode the base64 string. Convert the decoded data into a byte array and create a blob using the array. Once you have the blob, you’ll make use of the msSaveOrOpenBlob method to create PDF out of it.

downloadPdf(base64String, fileName){
  if(window.navigator && window.navigator.msSaveOrOpenBlob){ 
    // download PDF in IE
    let byteChar = atob(base64String);
    let byteArray = new Array(byteChar.length);
    for(let i = 0; i < byteChar.length; i++){
      byteArray[i] = byteChar.charCodeAt(i);
    }
    let uIntArray = new Uint8Array(byteArray);
    let blob = new Blob([uIntArray], {type : 'application/pdf'});
    window.navigator.msSaveOrOpenBlob(blob, `${fileName}.pdf`);
  } else {
    // Download PDF in Chrome etc.
    const source = `data:application/pdf;base64,${base64String}`;
    const link = document.createElement("a");
    link.href = source;
    link.download = `${fileName}.pdf`
    link.click();
  }
  onClickDownloadPdf(){
    let base64String = "your-base64-string";
    this.downloadPdf(base64String,"sample");
  }
}

Working source code for this tutorial can be found on GitHub.