How to use jsPDF with angular 2

GsMalhotra picture GsMalhotra · Jan 5, 2017 · Viewed 53.2k times · Source

I got an Error: jsPDF is not defined , I am currenty using following code :

import { Component, OnInit, Inject } from '@angular/core';
import 'jspdf';
declare let jsPDF;
@Component({
  ....
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

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

  download() {

        var doc = jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');    
        doc.save('Test.pdf');
    }
} 

I have install npm of jsPDF but don't know how import jspdf and run with angular-cli: 1.0.0-beta.17

Answer

GsMalhotra picture GsMalhotra · Jan 6, 2017

I have done it, after doing lot of R&D , their are few steps to follow as below : Install :

npm install jspdf --save

typings install dt~jspdf --global --save

npm install @types/jspdf --save

Add following in angular-cli.json:

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

html:

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

component ts:

import { Component, OnInit, Inject } from '@angular/core';
import * as jsPDF from 'jspdf'
@Component({
  ...
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

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

  download() {

        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');

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