Angular 8,使用 jspdf 和 autotable-jspdf 导入/使用问题

标签 angular typescript jspdf jspdf-autotable

Angular 8 - JSPDF 和 JSPDF-AutoTable

我需要在 html 中导出/生成一个基于 1 个网格的 pdf,但需要使用 css 更改一些 DOM,删除一些切换按钮并更改标题等,我发现的所有解决方案都有一些像简单窗口一样的打印效果。打印()。我也尝试过 pdfmake-wrapper 和 ngx-export-as,但它们没有 autoTable 魔法……最后一个 dom 更改被忽略,除非我使用 Renderer2 DOM 操作……但是我需要一个带有 css 类更改注入(inject)且没有 flick 的解决方案,所以我取回了 JSPDF。

我用 npm 安装了 jspdf 和 jspdf-autotable 包。

"dependencies": {
    ...
    "jspdf": "^1.5.3",
    "jspdf-autotable": "^3.2.4",
    ...
}

在 angular-cli.json 文件中,我嵌入了脚本:

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

在我的 component.ts 文件中,我按如下方式导入了这些文件:

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

我也试过这些行来导入 jspdf-autotable

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

我也尝试过另一种组合。

import jsPDF = require('jspdf');
import { autoTable as AutoTable } from 'jspdf-autotable';

但没有任何效果。

//在我的 component.ts 文件中,我使用的示例代码如下:

let columns = ["ID", "Name", "Age", "City"];
var data = [
    [1, "Jonatan", 25, "Gothenburg"],
    [2, "Simon", 23, "Gothenburg"],
    [3, "Hanna", 21, "Stockholm"]
];
const doc = new jsPDF(); // or let doc = new jsPDF.default();
doc.autoTable(columns, data);
doc.save("filename");

但是现在当我运行 node 命令来启动应用程序然后在调试期间,我收到如下错误:

a - 类型“jsPDF”上不存在属性“autoTable”。

b - 错误 TS2339:类型“typeof jsPDF”上不存在属性“default”。

有什么想法吗?

最佳答案

你必须使用如下。我有一段时间有同样的问题,但是在向开发人员询问后,我发现您必须使用 jsPdf() 的实例作为 autoTable() 函数的参数。休息如 documentation jsdpf的。

import { Component, OnInit } from '@angular/core';
import * as jsPDF from 'jspdf';
import autoTable from 'jspdf-autotable';

const doc = new jsPDF();

const columns = [['First Column', 'Second Column', 'Third Column']];
const data = [
['Data 1', 'Data 2', 'Data 3'],
['Data 1', 'Data 2', 'Data 3']
];

 autoTable(doc, {
      head: columns,
      body: data,
      didDrawPage: (dataArg) => { 
       doc.text('PAGE', dataArg.settings.margin.left, 10);
      }
 }); 

doc.save('table.pdf');

示例
源代码
https://codesandbox.io/s/currying-pine-wjp1g?file=/src/app/app.component.ts
现场演示
https://wjp1g.csb.app/

关于Angular 8,使用 jspdf 和 autotable-jspdf 导入/使用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58121653/

相关文章:

angular - Angular 的 HTTP 请求中不包含特定参数

node.js - getaddrinfo EAI_AGAIN registry.npmjs.org :80

angular - Http 请求头映射为空

Angular Material 2 'mat-button' 显示为常规按钮

javascript - 将 Firebase 与 Webpack 和 TypeScript 结合使用

javascript - jsPDF/jsPDF-autotable 将 dom 元素打印到表格中

javascript - jsPDF 不适用于 Chrome,仅适用于 Firefox 和 Safari

angular - 无法从另一个项目访问 Typescript 文件 - 项目引用

visual-studio - Visual Studio 认为一切都是 TypeScript 资源

node.js - 使用 node.js 时无法使用 jsPDF 添加图像