Introduction
In this article, I will explain how to generate pdf from html using JSDPF in angular. I will give example for generate pdf from html using JSDPF for better understanding.
This jsPDF plugin adds the ability to generate PDF tables either by parsing HTML tables or by using Javascript data directly.
Prerequisites
- Angular 12
- HTML/Bootstrap
For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:
Create Project
I have created a project using the following command in the Command Prompt.
ng new JsPDFExample
Open a project in Visual Studio Code using the following commands.
cd JsPDFExample
Code .
Now in Visual Studio, your project looks like as below.
Installation
Get jsPDF and this plugin by doing one of these things,
npm install jspdf jspdf-autotable
App.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule],
declarations: [ AppComponent, ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app.component.html
<div class="container">
<div class="row">
<div class="col-md-4" *ngFor="let img of images; let i = index">
<img
id="img{{ i }}"
class="img-fluid"
crossOrigin="Anonymous"
[src]="img.url"
/>
</div>
<div class="col-md-12 mt-3">
<button (click)="download()" class="btn btn-primary">Download PDF</button>
</div>
</div>
</div>
<table id="table">
<tr>
<th style="width:300px">Player</th>
<th style="width:100px">Span</th>
<th style="width:100px">Run</th>
</tr>
<tr>
<td>SR Tendulkar (INDIA)</td>
<td>1989-2012</td>
<td>18000</td>
</tr>
<tr>
<td>KC Sangakkara (Asia/ICC/SL)</td>
<td>2000-2015</td>
<td>14234</td>
</tr>
<tr>
<td>RT Ponting (AUS/ICC)</td>
<td>1995-2012</td>
<td>13704</td>
</tr>
<tr>
<td>ST Jayasuriya (Asia/SL)</td>
<td>1989-2011</td>
<td>13430</td>
</tr>
</table>
app.component.ts
import { Component, OnInit } from "@angular/core";
import jsPDF from "jspdf";
import "jspdf-autotable";
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
ngOnInit() {}
getBase64Image(img) {
var canvas = document.createElement("canvas");
console.log("image");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL;
}
download() {
let doc = new jsPDF();
doc.autoTable({html: '#table'});
doc.output('datauri','test.pdf');
}
}
Let's Run the Project
Now Click on download PDF Button pdf will download like as below:
Summary
In this article, I have discussed about implementation of JSPDF in Angular.