BLOGS

Export PDF in Angular with JSPDF

             In this Blog about Angular PDF Genration, 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:
  • jsPDF
  • PDFMake
  • ng2-pdf-viewer
However, In this Blog, we are going to focus only on jsPDF generator plugin to export the PDF in Angular.
 
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.
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”]
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 example 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"
    }
  ];
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: any = 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',
    },
  ];
  constructor() {}
  public openPDF(): void {
    let DATA: any = 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');
    });
  }
}

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

 ng serve --open 
output of Export PDF in Angular 13 with JSPDF