Angular 8, using jspdf and autotable-jspdf import/usage issues

Ernesto Casanova picture Ernesto Casanova · Sep 26, 2019 · Viewed 9.4k times · Source

Angular 8 - JSPDF & JSPDF-AutoTable

I need to export/generate one pdf base one grid in html, but is necessary some DOM changes with css, remove some toggle button and change header etc, and all solutions I found has some flicks in print like the simple window.print(). I tried also pdfmake-wrapper and ngx-export-as, but they don't have the autoTable magic...and the last one the dom changes are ignored, except if I use the Renderer2 DOM manipulation...but I need a solution with css class changes inject and no flick, so I get back the JSPDF.

I installed jspdf and jspdf-autotable packages with npm.

"dependencies": {
    ...
    "jspdf": "^1.5.3",
    "jspdf-autotable": "^3.2.4",
    ...
}

In angular-cli.json file, I have embedded the scripts:

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

In my component.ts file , I have imported these files as follows:

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

I have also tried these lines to import jspdf-autotable

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

I have also tried another combination.

import jsPDF = require('jspdf');
import { autoTable as AutoTable } from 'jspdf-autotable';

But nothing is working.

// In My component.ts file I'm using sample code as follows:

let columns = ["ID", "Name", "Age", "City"];
var data = [
    [1, "Jonatan", 25, "Gothenburg"],
    [2, "Simon", 23, "Gothenburg"],
    [3, "Hanna", 21, "Stockholm"]
];
const doc = new jsPDF(); // or let doc = new jsPDF.default();
doc.autoTable(columns, data);
doc.save("filename");

But now when I run the node command to start app then during debug, I'm getting errors as:

a - Property 'autoTable' does not exist on type 'jsPDF'.

b - Error TS2339: Property 'default' does not exist on type 'typeof jsPDF'.

Any idea?

Answer

Don Dilanga picture Don Dilanga · Jun 24, 2020

You have to use as following. I had the same question for a while, but after asking the question from the developers, I found that you have to use the instance of jsPdf() as an argument of autoTable() function. Rest goes as the documentation of jsdpf.

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

const doc = new jsPDF();

const columns = [['First Column', 'Second Column', 'Third Column']];
const data = [
['Data 1', 'Data 2', 'Data 3'],
['Data 1', 'Data 2', 'Data 3']
];

 autoTable(doc, {
      head: columns,
      body: data,
      didDrawPage: (dataArg) => { 
       doc.text('PAGE', dataArg.settings.margin.left, 10);
      }
 }); 

doc.save('table.pdf');

Example
Source Codes
https://codesandbox.io/s/currying-pine-wjp1g?file=/src/app/app.component.ts
Live Demo
https://wjp1g.csb.app/