如何在Angular 5中使用jsPDF和jspdf-autotable

6

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

"dependencies": {
    ...
    "jspdf": "^1.3.5",
    "jspdf-autotable": "^2.3.2"
    ...
}

以下是我的angular-cli.json文件(相关部分):

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

我的组件(相关部分):

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'.

我尝试使用以下代码替换我的组件中的导入:


// import * as jsPDF from 'jspdf';
// import 'jspdf-autotable';
declare var jsPDF: any;

如果没有编译时错误,但在运行downloadPDF()函数时出现以下提示:
ERROR ReferenceError: jsPDF is not defined
11个回答

15

Angular 5对我有效。

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

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

还需要将jspdf和jspdf-autotable文件添加到angular-cli.json中的脚本数组中。

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

在组件中不要导入jspdf或jspdf-autotable。

忘记以下的导入。



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


只需在@Component之前使用:

declare var jsPDF: any;

您的组件(相关部分):

declare var jsPDF: any;

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

1
感谢@Alciomar Hollanda,这对我很有帮助。 - Ali
在我的端上,我收到了“ReferenceError: jsPDF未定义”的错误。 - Miguel Ormita

10

我能够像这样取悦 TypeScript:

import jsPDF from 'jspdf';
import 'jspdf-autotable';
import { UserOptions } from 'jspdf-autotable';

interface jsPDFWithPlugin extends jsPDF {
  autoTable: (options: UserOptions) => jsPDF;
}
...
const doc = new jsPDF('portrait', 'px', 'a4') as jsPDFWithPlugin;
doc.autoTable({
  head: [['Name', 'Email', 'Country']],
  body: [
    ['David', 'david@example.com', 'Sweden'],
    ['Castille', 'castille@example.com', 'Norway']
  ]
});

适用于Angular 7(也适用于Angular 14)


这是最干净的解决方案。不确定为什么没有很多投票。 - fabricioflores
这功能很好,提供了清晰和逻辑的文档,尤其是类型定义。 - Miguel Ormita
我使用了"import { jsPDF } from 'jspdf';",而不是使用"import * as jsPDF"。 - Miguel Ormita

5

我正在使用Angular 7,但仅使用declare var jsPDF: any;不能正常工作。通过一些谷歌搜索,解决方案如下:

declare const require: any;
const jsPDF = require('jspdf');
require('jspdf-autotable');

当然,我从npm安装了模块,并将它们包含在angular.json的脚本数组中。对我来说它很好用。


转换HTML到PDF应该是一个微不足道的任务。谢谢你!这太棒了。 - Fariz
问题已经解决,这应该是被采纳的答案。 - ayed abboushi
这让我今天过得很愉快。 - Master Yoda

3
在angular-cli.json中。
"scripts": [
    "../node_modules/jspdf/dist/jspdf.min.js"
  ],

在你的项目中

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

这个对我有用。

2

首先你在 angular-cli.json 中声明了 .js 文件,应该将它们添加到 scripts 中。在你的配置中,你应该将 jspdf 脚本添加到 angular-cli.jsonscripts 中,所以:

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

那么你就不需要在组件中导入任何jspdf。只需使用declare var jsPdf: any即可。


1
谢谢。您的正确的.js文件应该在scripts数组中声明,我实际上已经在那里声明了 - 在问题中进行了修复。我的先前尝试是通过npm安装依赖项。这就是为什么我的package.json中的dependencies对象包括"jspdf": "^1.3.5","jspdf-autotable": "^2.3.2",devDependencies对象包括"@types/jspdf": "^1.1.31"。无论如何,我解决了我的问题。在下面回答我的问题。 - RIDVAN TANIK

1
在我的情况下,//@ts-ignore 起了作用...
//@ts-ignore
doc.autoTable(this.exportColumns, this.exportData);
doc.save('filename.pdf');

如果您的代码运行正常,但在ng serve和ng build期间显示autotable错误,则//@ts-ignore将为您在ng serve和ng build期间忽略错误检查。 只需将//@ts-ignore放置在显示错误的行上方即可。

你说得对,这个方法对我也有效。你能否解释一下 //@ts-ignore 的工作原理以及它是如何解决错误的?如果有类似的问题,这将非常有帮助。 - Shriram

1

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

npm install jspdf-autotable --save

请将jspdf和jspdf-autotable文件添加到angular-cli.json的scripts数组中,以便使用。
"scripts": [
    "../node_modules/jspdf/dist/jspdf.min.js",
    "../node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js"
],

在组件中不要导入jspdf或jspdf-autotable,只需
declare var jsPDF: any;

当然,在使用jspdf-autotable之前,您需要通过npm安装jspdf和@types/jspdf来进行开发。请注意,不要删除html标签。
npm install jspdf --save
npm install @types/jspdf --save-dev

1
如果您使用声明 var jsPDF: any;,它可以在Chrome、IE和其他浏览器中工作,但在Firefox浏览器中无法工作。在这种情况下,您可以按照以下步骤操作:
declare const require: any;
const jsPDF = require('jspdf');
require('jspdf-autotable');

其他部分保持不变,例如:
npm install jspdf --save
npm install @types/jspdf --save-dev
npm install jspdf-autotable --save

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

所以,它一定可以在所有浏览器上运行。 多么简单 :)

0

我解决了这个问题,首先导入Jspdf:import * as jsPDF from 'jspdf'; 然后我使用了一种代码模式,将jspdf autotable的内容复制并粘贴到jspdf.js中,这样对我来说就起作用了。

在官方网站上说你必须使用 //declare var jsPDF: any; // Important .但这在我的情况下不起作用,请尝试使用 import * as jsPDF from 'jspdf'; 代替。

在angular.json中的scripts部分:

"./node_modules/jspdf/dist/jspdf.min.js", "./node_modules/jspdf-autotable/dist/jspdf.plugin.autotable.js",


0

Angular 8 +

以下是我在Angular 8中的做法,请查看下面的示例,该示例使用faker服务生成虚拟用户,您可以将其更改为您的API响应。

通过npm安装软件包

npm i jspdf jspdf-autotable faker --save

安装类型

npm install @types/jspdf  @types/faker --save-dev

将以下条目添加到 angular.json 中

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

component.ts


import * as faker from 'faker'; // Not really require by jspdf or jsPDF-AutoTable 
declare var jsPDF: any;


@Component({
  selector: 'faker',
  templateUrl: './faker.component.html',
})


export class FakerPDFGeneratorComponent {



 headRows() {
    return [{id: 'ID', name: 'Name', email: 'Email', city: 'City', expenses: 'Sum'}];
  }

    footRows() {
    return [{id: 'ID', name: 'Name', email: 'Email', city: 'City', expenses: 'Sum'}];
  }

   bodyRows(rowCount) {
    rowCount = rowCount || 10;
    let body = [];
    for (var j = 1; j <= rowCount; j++) {
      body.push({
        id: j,
        name: faker.name.findName(),
        email: faker.internet.email(),
        city: faker.address.city(),
        expenses: faker.finance.amount(),
      });
    }
    return body;
  }

createPdf() {
    var doc = new jsPDF();

    doc.setFontSize(18);
    doc.text('With content', 14, 22);
    doc.setFontSize(11);
    doc.setTextColor(100);

    // jsPDF 1.4+ uses getWidth, <1.4 uses .width
    var pageSize = doc.internal.pageSize;
    var pageWidth = pageSize.width ? pageSize.width : pageSize.getWidth();
    var text = doc.splitTextToSize(faker.lorem.sentence(45), pageWidth - 35, {});
    doc.text(text, 14, 30);

    doc.autoTable({
      head: this.headRows(),
      body: this.bodyRows(40),
      startY: 50,
      showHead: 'firstPage'
    });

    doc.text(text, 14, doc.autoTable.previous.finalY + 10);

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

}

请随意尝试编码和演示

Edit Angular


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接