Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jsPDF in Angular 7? Gets jspdf__WEBPACK_IMPORTED_MODULE_2__.jsPDF is not a constructor error

Tags:

angular

jspdf

I am trying to use jsPDF in my Angular 7.1.3 project.

My package.json is below (related parts):

"dependencies": {
    "@angular/animations": "~7.1.0",
    "@angular/common": "~7.1.0",
    "@angular/compiler": "~7.1.0",
    "@angular/core": "~7.1.0",
    "@angular/forms": "~7.1.0",
    "@angular/platform-browser": "~7.1.0",
    "@angular/platform-browser-dynamic": "~7.1.0",
    "@angular/router": "~7.1.0",
    "core-js": "^2.5.4",
    "jspdf": "^1.5.3",
    "rxjs": "~6.3.3",
    "tslib": "^1.9.0",
    "zone.js": "~0.8.26"
  },

My component:

import { Component, ViewChild, ElementRef } from '@angular/core';
import { jsPDF } from 'jspdf';

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

  @ViewChild('pdfTable') pdfTable: ElementRef;


  public downloadAsPDF() {
    const doc = new jsPDF();

    const specialElementHandlers = {
      '#editor': function (element, renderer) {
        return true;
      }
    };

    const pdfTable = this.pdfTable.nativeElement;

    doc.fromHTML(pdfTable.innerHTML, 15, 15, {
      width: 190,
      'elementHandlers': specialElementHandlers
    });

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

There is no compile time error but running downloadAsPDF() function gives:

ERROR TypeError: "jspdf__WEBPACK_IMPORTED_MODULE_2__.jsPDF is not a constructor"

like image 413
Infojam Avatar asked Jan 31 '26 03:01

Infojam


2 Answers

The error is caused by the import statement

import { jsPDF } from 'jspdf';

Change to:

import jsPDF from 'jspdf';

like image 200
Infojam Avatar answered Feb 01 '26 19:02

Infojam


im using angular 10 and this works: const doc = new jspdf.jsPDF();

like image 33
Victor Victorio Nuñez Avatar answered Feb 01 '26 20:02

Victor Victorio Nuñez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!