How to Convert HTML into PDF Document in Angular 14

Angular convert HTML to PDF tutorial; in this lesson, you will learn how to easily convert an HTML template or page into PDF document in an Angular app using the jsPDF package.

Regardless of numerous HTML to PDF generator libraries available, however, we are going to use jsPDF in this tutorial.

The jsPDF is available through node package manager (NPM); it is an HTML5 client-side JavaScript solution for generating HTML to PDF.

PDF is a portable document format; generically, a PDF document is a read-only file often used to layout the data graphically.

PDFs are preferably used for creating eBooks, Tutorials, user manuals, forms for various applications and most importantly, for scanned documents.

Angular 14 Export HTML into PDF Example

To accomplish the task, we need to follow every step one by one mentioned below:

  • Step 1: Setting Up Angular Project
  • Step 2: Add Bootstrap Package
  • Step 3: Add jsPDF Package in Angular
  • Step 4: Implement HTML to PDF Conversion
  • Step 5: Export to PDF
  • Step 6: Start Angular Application

Setting Up Angular Project

Angular CLI is the tool that you need to begin with this tutorial, hence first add this profound tool on your machine:

npm install -g @angular/cli

Right after, the first step again type the suggested command to install new angular app:

ng new ng-demo-app

Next, get into the project root:

ng new ng-demo-app

Disable Strict Angular TypeStrict Errors

The latest version of Angular comes with strict mode, you have to manually disable the strict mode you can set “strict”: false, "noImplicitReturns": false and "strictTemplates": false inside the compilerOptions and angularCompilerOptions in tsconfig.json file.

Add Bootstrap Package

To swiftly create beautiful user interfaces components, add the Bootstrap package in angular, therefore install the Bootstrap library with the help of recommended command:

npm i bootstrap

To use the Bootstrap UI components in angular, set the styling of Bootstrap in angular.json config file:

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

Add jsPDF Package in Angular

This is the most important step of this tutorial, you have to install the jsPDF package in angular using the NPM command:

npm install jspdf

Implement HTML to PDF Conversion

We have installed the package, now you can import the jsPDF module in angular component and use it to convert HTML to PDF.

Consequently, open app.component.ts file and update the following code:

import { Component } 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 {

  Posts = [
    {
      "id": 1,
      "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
      "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
    },
    {
      "id": 2,
      "title": "qui est esse",
      "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
    },
    {
      "id": 3,
      "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
      "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
    },
    {
      "id": 4,
      "title": "eum et est occaecati",
      "body": "ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit"
    },
    {
      "id": 5,
      "title": "nesciunt quas odio",
      "body": "repudiandae veniam quaerat sunt sed\nalias aut fugiat sit autem sed est\nvoluptatem omnis possimus esse voluptatibus quis\nest aut tenetur dolor neque"
    },
    {
      "id": 6,
      "title": "dolorem eum magni eos aperiam quia",
      "body": "ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae"
    }
  ];

  constructor() { }

  public exportHtmlToPDF(){
    let data = document.getElementById('htmltable');
      
      html2canvas(data).then(canvas => {
          
          let docWidth = 208;
          let docHeight = canvas.height * docWidth / canvas.width;
          
          const contentDataURL = canvas.toDataURL('image/png')
          let doc = new jsPDF('p', 'mm', 'a4');
          let position = 0;
          doc.addImage(contentDataURL, 'PNG', 0, position, docWidth, docHeight)
          
          doc.save('exportedPdf.pdf');
      });
  }

}

Firstly, import jsPDF from “jspdf” package, likewise also import html2canvas from ‘html2canvas’ package.

Create some sample data that we will display into the HTML table, hence store it into the variable.

Additionally, create the exportHtmlToPDF() method; within this method, we will access the HTML data and take a snapshot of this table and export it to PDF using the html2canvas option.

Export to PDF and Download PDF File

Further, open app.component.html file and update the with the following code:

<div class="container">

  <button class="btn btn-primary btn-block" (click)="exportHtmlToPDF()">Download PDF</button>

  <div class="mt-5" id="htmltable" #htmltable>
    <table class="table table-bordered">
      <thead>
        <tr class="table-dagner">
          <th>#Post Id</th>
          <th>Body</th>
          <th>Title</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let post of Posts">
          <th scope="row">{{post.id}}</th>
          <td>{{post.body}}</td>
          <td>{{post.title}}</td>
        </tr>
      </tbody>
    </table>
  </div>

</div>

Display the Posts data using the ngFor directive, moreover define the id of the HTML element which needs to be exported to PDF.

Create a button using Bootstrap library, also attach a function that will transform HTML to PDF.

Start Angular Application

Execute recommended command to make the build and serve the angular application:

ng serve

Here is the link that you have to type on the browser to test the project:

http://localhost:4200

Conclusion

The angular HTML to PDF tutorial is completed; in this example guide, we learned using the simple method to convert HTML Table into PDF document and download effortlessly and recklessly HTML to PDF converted file in an angular application.