首页 > 解决方案 > 如何在 Angular 7 中使用 jsPDF?获取 jspdf__WEBPACK_IMPORTED_MODULE_2__.jsPDF 不是构造函数错误

问题描述

我正在尝试在我的 Angular 7.1.3 项目中使用 jsPDF。

我的 package.json 如下(相关部分):

"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"
  },

我的组件:

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');
  }
}

没有编译时错误,但运行 downloadAsPDF() 函数给出:

错误类型错误:“jspdf__WEBPACK_IMPORTED_MODULE_2__.jsPDF 不是构造函数”

标签: angularjspdf

解决方案


错误是由import语句引起的

import { jsPDF } from 'jspdf';

改成:

import jsPDF from 'jspdf';


推荐阅读