How to Generate or Export a PDF file in angular2/4/5/6 using jspdf?

First of all you need to install following javascript libraries

Run these commands

> npm install jspdf --save
> npm install @types/jspdf --save

Then add following line of code in angular-cli.json:

"scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ]


Create a component name it as 'pdfcomponent'

> ng g component 'pdfcomponent'


In pdfcomponent.component.html page add the follwoing code:

<button (click)="download()">download/export</button>

In pdfcomponent.component.ts page add the follwoing code:

import { Component, OnInit, Inject } from '@angular/core';
import * as jsPDF from 'jspdf'

@Component({
selector:'app-pdf',
templateUrl:'./pdf.component.html',
styleUrls: ['./pdf.component.css'],

providers: [
{ provide: 'Window', useValue: window }
]
})


export class PdfComponent implements OnInit {

constructor(
@Inject('Window') private window: Window,
) { }

ngOnInit() {
}

download() {

vardoc = new jsPDF();
doc.text(25, 25, 'Hello world!');
doc.text(25, 40, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(30, 30, 'http://www.sequelskills.com/');

// Save the PDF
doc.save('Test.pdf');
}

}
About Author: author 4 + years of Information Technology experience in understanding and analyzing the software and hardware engineering requirements, onsite and offshore management of product development. Expert work on design and development for windows,web,mobile Expert knowledge of C#,ADO.NET, ASP.Net MVC, ENTITY FRAMEWORK, LINQ,COLLECTIONS, JAVASCRIPT,AngularJs 1.0,Angular2, Jquery,Jquery-Ajax, SQL SERVER, XAML,Windows phone 8.1 Good knowledge of WCF-Restful services,WCF, WEB API-Services ,Web- Services,MIcrosoft-Azure,JUICE UI,HTML,CSS,AJAX Read More...

Join him on Google+ | Facebook | Linkedin

No comments