简体   繁体   中英

how to use jsPDF and jspdf-autotable in angular 5

I am trying to use jsPDF and jspdf-autotable in my Angular 5.2.0 project. My package.json is below (related parts):

"dependencies": {
    ...
    "jspdf": "^1.3.5",
    "jspdf-autotable": "^2.3.2"
    ...
}

My angular-cli.json is below (related parts):

"scripts": [
    ...
    "../node_modules/jspdf/dist/jspdf.min.js",
    "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
    ...
  ]

My component (related parts ):

import * as jsPDF from 'jspdf';
import 'jspdf-autotable';

@Component({
    selector: "energy-login",
    templateUrl: "./login.component.html",
    styleUrls: ["./login.component.scss"]
})
export class MyComponent implements OnInit {

    constructor() {}

    ngOnInit() {}

    downloadPDF() {

        let columns = ["ID", "Name", "Country"];
        let rows = [
            [1, "Shaw", "Tanzania"],
            [2, "Nelson", "Kazakhstan"],
            [3, "Garcia", "Madagascar"],
        ];

        let doc = new jsPDF('l', 'pt');
        doc.autoTable(columns, rows); // typescript compile time error
        doc.save('table.pdf');
    }
}

It says:

[ts] Property 'autoTable' does not exist on type 'jsPDF'.

I tried to replace imports in my component with

// import * as jsPDF from 'jspdf';
// import 'jspdf-autotable';
declare var jsPDF: any;

then there is no compile time error but while running downloadPDF() function it says :

ERROR ReferenceError: jsPDF is not defined

Is working for me Angular 5.

To work with jspdf-autotable in angular 5 , one must install jspdf and jspdf-autotable via npm

npm install jspdf --save
npm install @types/jspdf --save-dev
npm install jspdf-autotable --save

also add the jspdf and jspdf-autotable files to the scripts array in angular-cli.json

"scripts": [
"../node_modules/jspdf/dist/jspdf.min.js",
"../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
],

and in component never import jspdf or jspdf-autotable just.

Forget about the following import.

 
 
  
  
 
  

    import * as jsPDF from 'jspdf'; 
    import 'jspdf-autotable';


 

 
 

Just use Before @Component:

declare var jsPDF: any;

Your component (related parts ):

declare var jsPDF: any;

@Component({
    selector: "energy-login",
    templateUrl: "./login.component.html",
    styleUrls: ["./login.component.scss"]
})

export class MyComponent implements OnInit {

    constructor() {}

    ngOnInit() {}

    downloadPDF() {

        let columns = ["ID", "Name", "Country"];
        let rows = [
            [1, "Shaw", "Tanzania"],
            [2, "Nelson", "Kazakhstan"],
            [3, "Garcia", "Madagascar"],
        ];

        let doc = new jsPDF('l', 'pt');
        doc.autoTable(columns, rows); // typescript compile time error
        doc.save('table.pdf');
        }
    }

I was able to please TypeScript like this:

import * as jsPDF from 'jspdf';
import 'jspdf-autotable';
import { UserOptions } from 'jspdf-autotable';

interface jsPDFWithPlugin extends jsPDF {
  autoTable: (options: UserOptions) => jsPDF;
}
...
const doc = new jsPDF('portrait', 'px', 'a4') as jsPDFWithPlugin;
doc.autoTable({
  head: [['Name', 'Email', 'Country']],
  body: [
    ['David', 'david@example.com', 'Sweden'],
    ['Castille', 'castille@example.com', 'Norway']
  ]
});

Works in Angular 7.

I'm using angular 7, and just declare var jsPDF: any; doesn't work to me. After some googling, the solution was:

declare const require: any;
const jsPDF = require('jspdf');
require('jspdf-autotable');

And of course, I installed the modules from npm and include them into the scripts array in angular.json. It works fine to me.

In angular-cli.json

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

In your project

import * as jsPdf from 'jspdf';
import 'jspdf-autotable';

This work for me

First you have declared .js files in styles property in angular-cli.json , you should add them to scripts . In the configuration that you have, you should add your jspdf scripts to scripts in angular-cli.json , So:

"scripts": [ 
    "../node_modules/jspdf/dist/jspdf.min.js",
    "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
  ],

then you don't have to import any jspdf to your component. declare var jsPdf: any will be enough to use it.

To work with jspdf-autotable in angular 5, one must install jspdf and jspdf-autotable via npm

npm install jspdf-autotable --save

also add the jspdf and jspdf-autotable files to the scripts array in angular-cli.json

"scripts": [
    "../node_modules/jspdf/dist/jspdf.min.js",
    "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
],

and in component never import jspdf or jspdf-autotable just

declare var jsPDF: any;

Of course before working with jspdf-autotable one should install jspdf and for development @types/jspdf via npm

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

If you could use declare var jsPDF: any; it is working for Chrome, IE and other browsers too, but it is not working for Firefox browser.

In this case, you could follow the below steps:

declare const require: any;
const jsPDF = require('jspdf');
require('jspdf-autotable');

and other parts remain same like:

npm install jspdf --save
npm install @types/jspdf --save-dev
npm install jspdf-autotable --save
"scripts": [
    "../node_modules/jspdf/dist/jspdf.min.js",
    "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
],

So, it will defiantly work on all the browsers. how simple it is :)

I solved this issue, first import the Jspdf import * as jsPDF from 'jspdf'; i'm used a codesmells tatic, copied the content of jspdf autotable and pasted inside the jspdf.js, then works fine for me.

in the official site said you have to use //declare var jsPDF: any; // Important . it doesnt work in my case, try import * as jsPDF from 'jspdf'; instead.

in angular.json in scripts :

"./node_modules/jspdf/dist/jspdf.min.js", "./node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js",

Angular 8 +

This is how i did in Angular 8 please check below example which generate fake user using faker service, you can change it with your API response.

Install packages via npm

npm i jspdf jspdf-autotable faker --save

Install types

npm install @types/jspdf  @types/faker --save-dev

add below entries into angular.json

"scripts": [
              "node_modules/jspdf/dist/jspdf.min.js",
              "node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
            ]

component.ts


import * as faker from 'faker'; // Not really require by jspdf or jsPDF-AutoTable 
declare var jsPDF: any;


@Component({
  selector: 'faker',
  templateUrl: './faker.component.html',
})


export class FakerPDFGeneratorComponent {



 headRows() {
    return [{id: 'ID', name: 'Name', email: 'Email', city: 'City', expenses: 'Sum'}];
  }

    footRows() {
    return [{id: 'ID', name: 'Name', email: 'Email', city: 'City', expenses: 'Sum'}];
  }

   bodyRows(rowCount) {
    rowCount = rowCount || 10;
    let body = [];
    for (var j = 1; j <= rowCount; j++) {
      body.push({
        id: j,
        name: faker.name.findName(),
        email: faker.internet.email(),
        city: faker.address.city(),
        expenses: faker.finance.amount(),
      });
    }
    return body;
  }

createPdf() {
    var doc = new jsPDF();

    doc.setFontSize(18);
    doc.text('With content', 14, 22);
    doc.setFontSize(11);
    doc.setTextColor(100);

    // jsPDF 1.4+ uses getWidth, <1.4 uses .width
    var pageSize = doc.internal.pageSize;
    var pageWidth = pageSize.width ? pageSize.width : pageSize.getWidth();
    var text = doc.splitTextToSize(faker.lorem.sentence(45), pageWidth - 35, {});
    doc.text(text, 14, 30);

    doc.autoTable({
      head: this.headRows(),
      body: this.bodyRows(40),
      startY: 50,
      showHead: 'firstPage'
    });

    doc.text(text, 14, doc.autoTable.previous.finalY + 10);

    doc.save('table.pdf');
  }

}

Go ahead and play around with code and demo

编辑角度

In my case //@ts-ignore worked....

//@ts-ignore
doc.autoTable(this.exportColumns, this.exportData);
doc.save('filename.pdf');

If your code is running perfectly but showing autotable error during ng serve and ng build, then //@ts-ignore will work for you to ignore error check during ng serve and ng build. Just put //@ts-ignore above the line which is showing error.

Declare doc as any type. That will fix the error "[ts] Property 'autoTable' does not exist on type 'jsPDF'."

let doc:any = new jsPDF('l', 'pt');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM