Angular 8|9 Typescript | How to Download PDF/ EXCEL or other files instead of opening in new tab

In this tutorial, we will learn how to download any file type which can be a Doc, Excel, PDF or even images to file system instead of opening them in a new browser tab.

A simple task like downloading a file on the click of a link also sometimes proves so much challenging.

HTML 5 provides a very powerful attribute download which can be added to any <a> element tag to download almost any type of document or file instead of opening them to view.

Default Browser Behaviour

There are some situations where we simply want to use it to download a document. Due to the default behavior of a modern browser which opens the document like PDF in a new tab.

 Problem

We can’t enable you to download the file instead of opening them in a new browser tab which is also restricted sometimes for security reasons.

Solution

Here is a one-stop solution to this scenario.

Simply add the download attribute to the <a> element as shown below:

<a download href="assets/Docs/sample.pdf">Download</a>

 

Adding a custom name to the downloaded document

To add a custom name for the downloaded file, we can provide string value in the download attribute as shown below:

<a download="my-custom-file.pdf" href="assets/Docs/sample.pdf">Download</a>

Usage in Angular

To use in Angular, we can convert the href and download attributed to directives to take in dynamic values as shown below:

<a [download]="myFileName" [href]="fileUrl">Download</a>
export class DownloadComponent implements OnInit {

  myFileName = 'my-custom-file.pdf';
  fileUrl = 'assets/Docs/sample.pdf'

...
...

Note: Due to security reasons the download attribute follows same-origin policy so we need to provide same domain of file to be downloaded otherwise the download attribute will be ignored.

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *