Angular 7/8/9 | Download PDF Files in Browser Instead of Opening in New Tab Quick Solution

In Angular application, we may have a form where a user can upload documents in PDF formats and also can view and download the same in view mode.

By default when we add a link to PDF files in HTML, they open in a new tab from a user can download. This behavior is common in Chrome and Mozilla which are the most used web browsers.

In this tutorial, we will discuss how to force download PDF files in the user’s file systems when we click on a link instead of opening it in a new Tab. Along with that, we will also learn a bonus tip on how we can open a PDF file in tab starting from a specified page number.

So let’s get started!

Here we assume that you already have an Angular project up & running, if not you can create a new Angular project using the Ng CLI tool.

FileSaver.js Installation

To enable the download of PDF files, we need to install FileSaver package by running following NPM command in terminal:

After installing the above package, move to the component or service to create a method to download PDF files.

Here we have a basic component, where we will add a button to download PDF.

In the basic.component.ts file first, add the following code at the top of the component class.

As we are importing file-saver class methods using require, we need to declare it with type any otherwise Typescript will throw an error as shown below:

ERROR in src/app/basic/basic.component.ts(3,19): error TS2591: Cannot find name ‘require’. Do you need to install type definitions for node? Try npm i @types/node and then add node to the types field in your tsconfig.

Now add the following method to download PDF links using FileSaver.saveAs() method:

Above we have passed two arguments with the file path and file name.

You can dynamically pass both name and path in the method as well:

Use in HTML directly:


Bonus Tip!

How to open PDFs in the viewer starting from the specified Page number?

You may have a view for PDF files as shown below:

To open a PDF file at specific page use #page=3 parameter after pdf file like:

In HTML template use table with bootstrap CSS styles:

That’s it !

Make sure to have PDF file paths on the same server otherwise your server may throw CORS error while downloading the PDF file.

Leave a Reply

Notify of