Search code examples
angularjspdf

jsPDF multiple errors when trying to implement


I have a project where we are incorporating jsPDF and autotable but I have hit a wall..

Commands I ran:

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

angular.json:

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

ts file:

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


const doc = new jsPDF('portrait','px','a4');
    doc.autotable({
      head: [['Equipment_ID', 'Equipment_type_Description', 'Equipment_Description', 'Infrastructure_Name','Section_Name','Equipment_Condition','Equipment_Cost','Is_Active','Actions']],
      body: this.dataSource
    })

    doc.save("EquipmentList");


  }

error

Property 'autotable' does not exist on type 'jsPDF'

when I declare it like this:

declare var jsPDF: any;

and I ng serve, I get the following error:

An unhandled exception occurred: Script file ../node_modules/jspdf/dist/jspdf.min.js does not exist.
See "C:\Users\reube\AppData\Local\Temp\ng-4iWKp5\angular-errors.log" for further details.

Solution

  • 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 or angular.json) depends on your angular version

        "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;