Convert HTML Table To PDF Using html2pdf.js In Angular 12

In this article, we are going to discuss how to convert html table to pdf using html2pdf.js in Angular 12 application. Html2PDF is a library which helps us to convert html table into pdf document very easily. It provides an easy way to generate pdf documents from html data. We can also customize the generated pdf document according to our requirements.

Let start by creating a new project in Angular and name it html2pdf

ng new html2pdf

To convert html table to pdf, we need to install html2pdf library using npm.

npm i html2pdf.js

Once you have installed the library, copy paste the below Angular code to app.component.html file.

app.component.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

<!-- DevShed.org -->
<div class="container">
  <h2>HTML to PDF using Angular</h2>
  <p>Something Here</p>            
  <table id="table" class="table table-striped">
    <thead>
      <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Dohn</td>
        <td>Joe</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>Ary</td>
        <td>May</td>
        <td>[email protected]</td>
      </tr>
      <tr>
        <td>Duly</td>
        <td>Jooley</td>
        <td>[email protected]</td>
      </tr>
    </tbody>
  </table>
</div>
<button (click)="download()">Download PDF Now</button>
<p><a href="https://www.devshed.org/">Powered by DevShed.org</a></p>
<!-- DevShed.org -->
</body>
</html>

app.component.ts

import { Component } from "@angular/core";
import * as html2pdf from 'html2pdf.js'

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  
  download(){
    var element = document.getElementById('table');
var opt = {
  margin:       1,
  filename:     'output.pdf',
  image:        { type: 'jpeg', quality: 0.98 },
  html2canvas:  { scale: 2 },
  jsPDF:        { unit: 'in', format: 'letter', orientation: 'portrait' }
};
 
// DevShed.org
html2pdf().from(element).set(opt).save();
  }

}

Next add below code to your tsconfig.json file (right below “”noImplicitReturns”: true,”.).

"noImplicitAny": false,

Now compile and run using the below command

ng server --open

That’s all we need to do to convert html table to pdf using html2pdf library in Angular 12 application. Thanks for reading and I hope you found this article helpful.