How to Convert HTML to PDF in Angular Application?

In this article we will see how to convert HTML to pdf in Angular application. We will see how to create PDF from HTML in angular application. and we will also see how to export HTML data as pdf in Angular application.

PDF or “portable document format” is used when you need to save files that cannot be modified but still need to be easily shared and printed. Today almost everyone has Adobe Reader or other program on their computer a version of Adobe Reader or other program on their computer that can read a PDF file.

When do you need convert HTML to PDF in Angular application?

When you develop a shopping or ticket booking application. You often provide feature to download an invoice, ticket etc. So for this, you have to add the option to export PDF in your Angular application.

To create PDF from HTML in angular app, we need to install the following npm packages:

Now we will see all the steps to convert HTML to PDF in Angular application.

1) Create Angular App

Run the following command to create new angular project

ng new angular-html-to-pdf-demo

2) Install npm packages

Now we will install all required package that will help us to convert html to pdf document in angular.

npm install pdfmake --save
npm install html-to-pdfmake --save
npm install jspdf --save

3) Update Component Logic

Now we will update component file where we will implement downloadAsPDF() function as shown below


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

declare var require: any;

import * as pdfMake from "pdfmake/build/pdfmake";
import * as pdfFonts from "pdfmake/build/vfs_fonts";
const htmlToPdfmake = require("html-to-pdfmake");
(pdfMake as any).vfs = pdfFonts.pdfMake.vfs;

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
export class AppComponent {

  @ViewChild('pdfTable') pdfTable!: ElementRef;
  public exportPDF() {
    const pdfTable = this.pdfTable.nativeElement;
    var html = htmlToPdfmake(pdfTable.innerHTML);
    const documentDefinition = { content: html };

4) Update Component Template File

Now update template file which will show HTML table and 1 button to export/download as PDF.


<div class="container">
  <div id="pdfTable" #pdftable="">
    <h2>Angular HTML To PDF Example</h2>
    <table class="table">
          <td>Zoller </td>
  <button class="btn btn-primary" (click)="exportPDF();">Export To PDF</button>

5) Run Angular App

Now you can run the angular app using ng serve command. and you will see the following output.

and we are done with converting HTML to PDF in angular application.

I hope you like this article.

Also Read: