Angular 10/9/8 PDF Tutorial – Export PDF in Angular with JSPDF

Last updated on by Digamber
In this Angular 10/9/8 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 10/9/8.

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 library in the same component, from where we have to export PDF to Angular.

import * as jsPDF from 'jspdf'

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"
    }
  ];

The openPDF() function export the PDF from HTML data. We used ViewChild and ElementRef services to access the DOM access to get the content.

The DATA var stores the HTML table content, the new jsPDF() method allows us to export PDF.

 public openPDF():void {
    let DATA = this.htmlData.nativeElement;
    let doc = new jsPDF('p','pt', 'a4');
    doc.fromHTML(DATA.innerHTML,15,15);
    doc.output('dataurlnewwindow');
  }

Download PDF in Angular

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

public downloadPDF():void {
    let DATA = this.htmlData.nativeElement;
    let doc = new jsPDF('p','pt', 'a4');

    let handleElement = {
      '#editor':function(element,renderer){
        return true;
      }
    };
    doc.fromHTML(DATA.innerHTML,15,15,{
      'width': 200,
      'elementHandlers': handleElement
    });

    doc.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" #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 open and download PDF button.

<div class="col-md-4 text-right">
   <button class="btn btn-success btn-block" (click)="openPDF()">Open PDF</button>
   <button class="btn btn-danger btn-block" (click)="downloadPDF()">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 * as jsPDF from 'jspdf'

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

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 = this.htmlData.nativeElement;
    let doc = new jsPDF('p','pt', 'a4');
    doc.fromHTML(DATA.innerHTML,15,15);
    doc.output('dataurlnewwindow');
  }


  public downloadPDF():void {
    let DATA = this.htmlData.nativeElement;
    let doc = new jsPDF('p','pt', 'a4');

    let handleElement = {
      '#editor':function(element,renderer){
        return true;
      }
    };
    doc.fromHTML(DATA.innerHTML,15,15,{
      'width': 200,
      'elementHandlers': handleElement
    });

    doc.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" #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()">Open PDF</button>
      <button class="btn btn-danger btn-block" (click)="downloadPDF()">Download PDF</button>
    </div>

  </div>
</div>

Export PDF in Angular 10/9/8

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!