Angular 16 PDF Tutorial – Export PDF in Angular with JSPDF

Last Updated on by in Angular

PDFs are handy files allow to display text and images content to the users. In this tutorial, we will learn how to export PDF file using Angular component and the jsPDF package.

To download the PDF in Angular, we will use the Bootstrap UI component. Bootstrap is a styling library meant to shorten the HTML and CSS writing work in frontend development.

jsPDF is a powerful library to export HTML to PDF file in Angular. The jsPDF package offers handy methods that allows to:

  • Export HTML pages to PDF
  • Download the PDF generated files.
  • Fit DOM content within the paper size
  • Customize the PDF format
  • Alter the PDF orientation
  • Alter the content size
  • Export HTML table in PDF view with regards to Angular

What is a PDF File?

JSPDF is a JavaScript library allows to generate PDF files dynamically in a web browser. It offers a simplest way to create, modify, and download PDF documents using JavaScript.

JSPDF is quite often used in web application development to generate reports, invoices, receipts, and other types of documents that need to be saved or printed as PDF files.

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 file.

"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 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: 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',
    },
    {
      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: 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');
    });
  }
}

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>

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

ng serve --open

Export PDF in Angular 13

Conclusion

By using jsPDF, we can create PDF documents from absolute beginning as well as modify existing PDF files.

It supports a wide array of features, including adding text, images, shapes, tables, and interactive elements like links and form fields.

In this guide, we have learned through series of steps; how to export PDF data from browser using the latest version of Angular and jsPDF package.

Thank you for reading, and I hope you enjoy and share this lesson!

Suggested Links

Reference: jspdf
Reference: Bootstrap