How to Download PDF files in Angular Instead of Viewing in New Tab

In an application, when we have PDF file links, they are usually opened in a new tab instead of downloading them. In this quick tutorial, we will discuss how to enable PDF file download when the user clicks on a link using a simple technique.

To download a PDF file in Angular instead of viewing it in a new tab, you can use the HttpClient module provided by Angular. Here are the steps:

  1. Import required modules and dependencies
  2. Inject the HttpClient module in your component
  3. Make a GET request to the URL of the PDF file using HttpClient
  4. Convert the response to a Blob object using the blob() method
  5. Save the file using the saveAs() function from the file-saver library
  6. Call the downloadPDF() method from the component template

 

Step 1 – Import the HttpClient module and the saveAs function from the file-saver library in your component.

import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';

Step 2 – Inject the HttpClient module in your constructor.

constructor(private http: HttpClient) {}

Step 3 – In your method that downloads the PDF file, make a GET request to the URL of the PDF file using the HttpClient module. Then, convert the response to a Blob object using the blob() method.

downloadPDF() {
  const url = 'https://example.com/path/to/file.pdf';
  this.http.get(url, { responseType: 'blob' }).subscribe((response: Blob) => {
    // handle the response here
  });
}

Step 4 – Once you have the Blob object, use the saveAs() function from the file-saver library to save the file. The first argument is the Blob object, and the second argument is the name of the file.

downloadPDF() {
  const url = 'https://example.com/path/to/file.pdf';
  this.http.get(url, { responseType: 'blob' }).subscribe((response: Blob) => {
    saveAs(response, 'file.pdf');
  });
}

Step 5 – Call the downloadPDF() method from your component template when the user clicks a button or a link.

<button (click)="downloadPDF()">Download PDF</button>

Conclusion:

In conclusion, downloading PDF files in Angular is a simple process that can be achieved using the HttpClient module and the file-saver library. By following the steps outlined above, developers can provide a better user experience by allowing users to download PDF files instead of opening them in a new tab. It’s important to note that the saveAs() function from the file-saver library is only available in modern browsers. Overall, this solution provides an efficient and user-friendly way of downloading PDF files in Angular.

Leave a Comment

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