Typescript - how to correctly use jsPDF in Angular2?

22,533

Solution 1

Using jspdf with the latest angular cli version is really easy. Simply install jspdf from npm and use it something like this:

app.component.ts

// Note that you cannot use import jsPDF from 'jspdf' if you 
// don't install jspdf types from DefinitelyTyped
let jsPDF = require('jspdf');
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor() {
    let doc = new jsPDF();
    doc.text("Hello", 20, 20);
    doc.save('table.pdf');
  }
}

For old versions of angular cli based on systemjs instead of webpack

Here is a link to a description of one way to work with the angular-cli and libraries in umd or plain javascript. It basically involves using declare jsPDF: any together with importing the library in systemjs vendor files.

Solution 2

The way you would do using Angular-cli and Angular 4 is first add jspdf to Scripts array in .angular-cli.json

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

then in the component add the following

import * as JSPdf from 'jspdf'; 

then in your class

  generatePdf() {
    let doc = new JSPdf();
    doc.text("Hello", 20, 20);
    doc.save('table.pdf');
}
Share:
22,533
Sudha
Author by

Sudha

Updated on July 18, 2022

Comments

  • Sudha
    Sudha almost 2 years

    I have created an Angular2 application that generates JSON data. I want to save this JSON output into a file, preferably a PDF file. This application is written using Typescript.

    I have used jsPDF for writing the JSON data into a PDF file. I have installed jsPDF package via npm using npm install jspdf --save. I have also added necessary links in index.html page. I made these changes to my application when it was running. I was able to save the JSON data to the file.

    When I stopped and restarted the application, it did not start as expected. I got the following error:

    [email protected] start C:\Users*****\Documents\Projects\Angular\json-to-pdf

    tsc && concurrently "npm run tsc:w" "npm run lite"

    app/components/app.component.ts(35,19): error TS2304: Cannot find name 'jsPDF'.

    I'm adding the code that I have used.

    package.json:

    "dependencies": {
         "@angular/common": "2.0.0-rc.1",
         "@angular/compiler": "2.0.0-rc.1",
         "@angular/core": "2.0.0-rc.1",
         "@angular/http": "2.0.0-rc.1",
         "@angular/platform-browser": "2.0.0-rc.1",
         "@angular/platform-browser-dynamic": "2.0.0-rc.1",
         "@angular/router": "2.0.0-rc.1",
         "@angular/router-deprecated": "2.0.0-rc.1",
         "@angular/upgrade": "2.0.0-rc.1",
         "angular2-in-memory-web-api": "0.0.7",
         "bootstrap": "^3.3.6",
         "es6-shim": "^0.35.0",
         "jquery": "^2.2.4",
         "jspdf": "^1.2.61",
         "reflect-metadata": "^0.1.3",
         "rxjs": "5.0.0-beta.6",
         "systemjs": "0.19.27",
         "zone.js": "^0.6.12"
    }
    

    index.html:

    <html>
      <head>
        <title>JSON to PDF</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        ....
    
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
    
        ....
    
      </head>
    
      <!-- 3. Display the application -->
      <body class="bg">
        <div>
          <app>Loading...</app>
        </div>
      </body>
    </html>
    

    app.component.ts:

     import {Component} from '@angular/core';
     @Component({
       selector: 'app',
       template: `<button (click)="createFile()">Export JSON to PDF</button>`
     })
     export class AppComponent {
         public item = {
            "Name" : "XYZ",
             "Age" : "22",
             "Gender" : "Male"
         }
         constructor() {}
         createFile(){
            var doc = new jsPDF();
            var i=0;
            for(var key in this.item){
               doc.text(20, 10 + i, key + ": " + this.item[key]);
               i+=10;
            }
            doc.save('Test.pdf');
        }
     }
    

    I think some import statement is missing in the app.component.ts file. Can someone point to the correct import statement if that is what is missing? If that is the error that I have made, can I know how to correctly us jsPDF in Angular2?

    Thank you.

  • Beckham_Vinoth
    Beckham_Vinoth almost 8 years
    Still facing that same Error !!!! How to use that jspdf in Typescript ?
  • Simon Bengtsson
    Simon Bengtsson almost 8 years
    Oops, included the wrong vendor file in angular-cli-build.js. Try the updated config above.
  • Beckham_Vinoth
    Beckham_Vinoth almost 8 years
    @ Simon Bengtsson , See here my question is different :( I didn't find any files like app.component.ts,src/system-config.ts,angular-cli-build.js in my application . I have to find out first so that i can implement the steps as you mentioned in your answer .
  • Simon Bengtsson
    Simon Bengtsson almost 8 years
    This answer is mainly for people who use the angular-cli, but could be taken as inspiration for other systemjs projects. If you have another setup it would probably be easier if you created a new question where you can describe more in detail your code and build config. Feel free to ping me after that and I'll take a look.
  • Beckham_Vinoth
    Beckham_Vinoth almost 8 years
    @ Simon Bengtsson, Help me out from this if it's possible -----> stackoverflow.com/questions/38661808/…
  • Sudha
    Sudha almost 8 years
    I have added the above changes but I'm getting a new error. zone.js:461 Unhandled Promise rejection: Error: XHR error (404 Not Found) loading http://localhost:4200/vendor/jspdf/dist/jspdf.min.js
  • Sudha
    Sudha almost 8 years
    I was able to solve the error. I had do typings install dt~jspdf --global --save and restart the application. Thank you.
  • user2828442
    user2828442 almost 7 years
    How can i add scripts in my ionic project ? i have installed jspdf using npm , stuck what to do next
  • Anil Agrawal
    Anil Agrawal over 6 years
    even if you have installed jspdf using npm, there will be files like below directory structure node_modules/jspdf/dist/jspdf.min.js, you should add given lines as it is under list of scripts in specified file .angular-cli.json
  • Joe Aspara
    Joe Aspara over 5 years
    In my case the relative path to node_modules starts from the same directory so I used "./node_modules/jspdf/dist/jspdf.min.js". Anyway this is the only answer that did the trick for me.