如何在angular 5中使用jsPDF和jspdf-autotable [英] how to use jsPDF and jspdf-autotable in angular 5

查看:777
本文介绍了如何在angular 5中使用jsPDF和jspdf-autotable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Angular 5.2.0项目中使用jsPDF和jspdf-autotable.我的package.json在下面(相关部分):

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

我的angular-cli.json在下面(相关部分):

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

它说:

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

然后没有编译时错误,但在运行downloadPDF()函数时显示:

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

ERROR ReferenceError: jsPDF is not defined

推荐答案

要在Angular 5中使用jspdf-autotable,必须通过npm安装jspdf和jspdf-autotable

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

npm install jspdf-autotable --save

还将jspdf和jspdf-autotable文件添加到angular-cli.json中的scripts数组中

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

并且在组件中永远不要仅导入jspdf或jspdf-autotable

and in component never import jspdf or jspdf-autotable just

declare var jsPDF: any;

当然,在使用jspdf-autotable之前,应该先安装jspdf并通过npm开发@ types/jspdf

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

这篇关于如何在angular 5中使用jsPDF和jspdf-autotable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆