Welcome folks today in this blog post we will be using the jspdf
library to export dynamic pdf
using html5 template
and download it using filesaver.js
library using typescript in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new angular
project using the below command as shown below
ng new sampleproject
cd sampleproject
And after that you need to install the below libraries
using the below command as shown below
npm i jspdf
npm i file-saver
And after that you will see the below directory
structure of the angular app as shown below
And now we need to go to app.component.html
file and copy paste the following code
app.component.html
1 |
<button (click)="generatePDF()">Download PDF</button> |
As you can see in the above html
code we have the simple button
where we have assinged the click
event handler where we are executing the generatePDF()
method as shown below.
And now we need to go to app.component.ts
file and copy paste the below code
app.component.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import { Component } from '@angular/core'; import jspdf from 'jspdf'; import * as FileSaver from 'file-saver'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent { title = 'dsf'; pdfSrc: any; data = { name: 'John Doe', email: 'john.doe@example.com', }; generatePDF() { const doc = new jspdf(); const content = `Name: ${this.data.name}\nEmail: ${this.data.email}`; doc.text(content, 10, 10); const pdf = doc.output('blob'); FileSaver.saveAs(pdf, 'template.pdf'); } } |
As you can see in the above typescript
code we have defined the generatePDF()
method where we are initializing the jspdf
constructor and then we are embedding the name
and the email
using the object. And then we are converting to base64
data url and then we are downloading the pdf document as an attachment using the filesaver.js
library.