Angular 12 PDF Tutorial – Export PDF in Angular with JSPDF

Last updated on: by Editorial Team
In this Angular 12 PDF tutorial, i am going to share with you how to export PDF file in Angular application using the jsPDF package.

We can generate PDF for various documents such as invoices, reports, forms etc. In a web application, we can create pdf using Browser print methods, third party tool, and we can also download the PDF on the client-side.

There are few other PDF packages available such as:

However, In this post, we are going to focus only on jsPDF generator plugin to export the PDF in Angular 12.

The jsPDF is a JavaScript-based module, It is used to generate PDFs on the client-side, and it offers the large number of methods that allows you to customize the PDF view easily.

You can check out the official documentation here.

What is a PDF File?

Adobe formulated PDF at around 1990s. It has two primary goals. The first goal was that users should be able to open the documents on any hardware or operating system. The second goal was that whenever a user opens a PDF document that must look the same.

PDFs include text, images, embedded fonts, hyperlinks, video, interactive buttons, forms, and more.

Setup Angular Project

Use command via Angular CLI to create a brand new Angular project.

ng new angular-pdf

Next, start the angular app in your favourite IDE.

Install Bootstrap

To handle the UI part, we should install the Bootstrap library in Angular. We will be using the Bootstrap table UI component, this table will hold the data which we will convert to PDF.

npm install bootstrap

Include the CSS path of Bootstrap in styles array in the angular.json.

"styles": [
    "src/styles.css",
    "node_modules/bootstrap/dist/css/bootstrap.min.css"
]

Use the following command to start the app in the browser.

ng serve --open

Install jsPDF Package

Next, install the jsPDF package in your angular application using the below command.

npm install jspdf

We have to import the jsPDF and html2canvas libraries in the same component, from where we have to export PDF to Angular.

import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

Add Fake Data

We need to show some random data, so, declare a variable with some fake user data.

USERS = [
    {
      "id": 1,
      "name": "Leanne Graham",
      "email": "sincere@april.biz",
      "phone": "1-770-736-8031 x56442"
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "email": "shanna@melissa.tv",
      "phone": "010-692-6593 x09125"
    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "email": "nathan@yesenia.net",
      "phone": "1-463-123-4447",
    },
    {
      "id": 4,
      "name": "Patricia Lebsack",
      "email": "julianne@kory.org",
      "phone": "493-170-9623 x156"
    },
    {
      "id": 5,
      "name": "Chelsey Dietrich",
      "email": "lucio@annie.ca",
      "phone": "(254)954-1289"
    },
    {
      "id": 6,
      "name": "Mrs. Dennis",
      "email": "karley@jasper.info",
      "phone": "1-477-935-8478 x6430"
    }
  ];

Download PDF in Angular

To download the PDF, we call the new jsPDF() object and define the PDF size in it. The PDF.save() function takes the Downloaded PDF’s name as an argument.

public openPDF():void {
let DATA = document.getElementById('htmlData');
    
html2canvas(DATA).then(canvas => {
    
    let fileWidth = 208;
    let fileHeight = canvas.height * fileWidth / canvas.width;
    
    const FILEURI = canvas.toDataURL('image/png')
    let PDF = new jsPDF('p', 'mm', 'a4');
    let position = 0;
    PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight)
    
    PDF.save('angular-demo.pdf');
});     
}

Bootstrap Table View

Use the Bootstrap’s class and UI modules to build the Table and add the dynamic data into it.

<div class="col-md-8" id="htmlData">
    <table class="table table-bordered">
        <tr class="table-primary">
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
        <tr *ngFor="let user of USERS">
            <th>{{user.id}}</th>
            <td>{{user.name}}</td>
            <td>{{user.email}}</td>
            <td>{{user.phone}}</td>
        </tr>
    </table>
</div>

Next, add the download PDF button with the given below code.

<div class="col-md-4 text-right">
    <button class="btn btn-success btn-block" (click)="openPDF()">Download PDF</button>
</div>

The Final Code

Next, open app.component.ts file and add the following code.

import { Component, ViewChild, ElementRef } from '@angular/core';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {

  @ViewChild('htmlData') htmlData:ElementRef;

  USERS = [
    {
      "id": 1,
      "name": "Leanne Graham",
      "email": "sincere@april.biz",
      "phone": "1-770-736-8031 x56442"
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "email": "shanna@melissa.tv",
      "phone": "010-692-6593 x09125"
    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "email": "nathan@yesenia.net",
      "phone": "1-463-123-4447",
    },
    {
      "id": 4,
      "name": "Patricia Lebsack",
      "email": "julianne@kory.org",
      "phone": "493-170-9623 x156"
    },
    {
      "id": 5,
      "name": "Chelsey Dietrich",
      "email": "lucio@annie.ca",
      "phone": "(254)954-1289"
    },
    {
      "id": 6,
      "name": "Mrs. Dennis",
      "email": "karley@jasper.info",
      "phone": "1-477-935-8478 x6430"
    }
  ];

  constructor() { }

  public openPDF():void {
    let DATA = document.getElementById('htmlData');
      
    html2canvas(DATA).then(canvas => {
        
        let fileWidth = 208;
        let fileHeight = canvas.height * fileWidth / canvas.width;
        
        const FILEURI = canvas.toDataURL('image/png')
        let PDF = new jsPDF('p', 'mm', 'a4');
        let position = 0;
        PDF.addImage(FILEURI, 'PNG', 0, position, fileWidth, fileHeight)
        
        PDF.save('angular-demo.pdf');
    });     
  }
 
}

Then, open app.component.html file and add the following code.

<div class="container">
  <div class="row">

    <div class="col-md-8" id="htmlData">
      <table class="table table-bordered">
        <tr class="table-primary">
          <th>Id</th>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
        </tr>
        <tr *ngFor="let user of USERS">
          <th>{{user.id}}</th>
          <td>{{user.name}}</td>
          <td>{{user.email}}</td>
          <td>{{user.phone}}</td>
        </tr>
      </table>
    </div>

    <div class="col-md-4 text-right">
      <button class="btn btn-success btn-block" (click)="openPDF()">Download PDF</button>
    </div>

  </div>
</div>

Export PDF in Angular 12

Well, this is it. We have learned how to export data in Angular with jsPDF package. I hope you will like and share this tutorial, thanks for reading!