angular - 如何将 jsPDF 与 angular 2 一起使用

标签 angular jspdf angular2-cli

我收到错误:未定义 jsPDF,我目前正在使用以下代码:

import { Component, OnInit, Inject } from '@angular/core';
import 'jspdf';
declare let jsPDF;
@Component({
  ....
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

  constructor(
    @Inject('Window') private window: Window,
    ) { }

  download() {

        var doc = jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');    
        doc.save('Test.pdf');
    }
} 

我已经安装了 jsPDF 的 npm,但不知道如何导入 jspdf 并使用 angular-cli 运行:1.0.0-beta.17

最佳答案

我已经做到了,经过大量的研发,他们的步骤如下: 安装:

npm install jspdf --save

typings install dt~jspdf --global --save

npm install @types/jspdf --save

在 angular-cli.json 中添加以下内容:

"scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ]

html:

<button (click)="download()">download </button>

组件 ts:

import { Component, OnInit, Inject } from '@angular/core';
import * as jsPDF from 'jspdf'
@Component({
  ...
  providers: [
    { provide: 'Window',  useValue: window }
  ]
})
export class GenratePdfComponent implements OnInit {

  constructor(
    @Inject('Window') private window: Window,
    ) { }

  download() {

        var doc = new jsPDF();
        doc.text(20, 20, 'Hello world!');
        doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
        doc.addPage();
        doc.text(20, 20, 'Do you like that?');

        // Save the PDF
        doc.save('Test.pdf');
    }
}

关于angular - 如何将 jsPDF 与 angular 2 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484323/

相关文章:

angular - 未捕获的类型错误 : this. _input.charCodeAt 不是函数

javascript - 带 Electron 的 Angular2 CLI

angular - Angular 7 应用程序在 Tomcat 上的图像路径

angular - reCAPTCHA v3 网络密集型 Web 应用程序

angular - 在列值更改时禁用 Angular 表的自动排序

javascript - 未捕获的类型错误 : Cannot read property 'cells' of undefined jspdf

angular - RXJS - Angular - 取消订阅主题

jquery - 使用 html2canvas 和 jspdf 创建的 PDF 文件 - pdf 中不允许选择文本

node.js - NodeJs 用 jsPDF 说 "ReferenceError: window is not defined"

angular - 类型错误 : Cannot read property 'directoryExists' of undefined