我创建了一个生成JSON数据的Angular2应用程序。我想将此JSON输出保存到文件中,最好是PDF文件。此应用程序使用Typescript编写。
我使用jsPDF将JSON数据写入PDF文件。我已经使用npm install jspdf --save
通过npm安装了jsPDF包。我还在index.html页面中添加了必要的链接。我在运行时对应用程序进行了这些更改。我能够将JSON数据保存到文件中。
当我停止并重新启动应用程序时,它没有按预期启动。我收到以下错误:
json-excel@1.0.0启动C:\ Users ***** \ Documents \ Projects \ Angular \ json-to-pdf
tsc&&同时" npm run tsc:w" " npm run lite"
app / components / app.component.ts(35,19):错误TS2304:找不到姓名' jsPDF'。
我添加了我用过的代码。
的package.json:
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.1",
"angular2-in-memory-web-api": "0.0.7",
"bootstrap": "^3.3.6",
"es6-shim": "^0.35.0",
"jquery": "^2.2.4",
"jspdf": "^1.2.61",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"systemjs": "0.19.27",
"zone.js": "^0.6.12"
}
的index.html:
<html>
<head>
<title>JSON to PDF</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
....
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>
....
</head>
<!-- 3. Display the application -->
<body class="bg">
<div>
<app>Loading...</app>
</div>
</body>
</html>
app.component.ts:
import {Component} from '@angular/core';
@Component({
selector: 'app',
template: `<button (click)="createFile()">Export JSON to PDF</button>`
})
export class AppComponent {
public item = {
"Name" : "XYZ",
"Age" : "22",
"Gender" : "Male"
}
constructor() {}
createFile(){
var doc = new jsPDF();
var i=0;
for(var key in this.item){
doc.text(20, 10 + i, key + ": " + this.item[key]);
i+=10;
}
doc.save('Test.pdf');
}
}
我认为app.component.ts文件中缺少一些import语句。有人指出正确的导入语句,如果这是缺少的吗?如果那是我犯的错误,我可以知道如何正确使用Angular2中的jsPDF吗?
谢谢。
答案 0 :(得分:8)
将jspdf与最新的角度cli版本一起使用非常简单。只需从npm安装jspdf并使用如下:
<强> app.component.ts 强>
// Note that you cannot use import jsPDF from 'jspdf' if you
// don't install jspdf types from DefinitelyTyped
let jsPDF = require('jspdf');
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor() {
let doc = new jsPDF();
doc.text("Hello", 20, 20);
doc.save('table.pdf');
}
}
对于基于systemjs而不是webpack的旧版角度cli
Here is a link描述了使用angular-cli
中的umd
和库或普通javascript中的库的一种方法。它基本上涉及使用declare jsPDF: any
和在systemjs供应商文件中导入库。
答案 1 :(得分:4)
使用Angular-cli和Angular 4的方式是 首先将jspdf添加到.angular-cli.json
中的Scripts数组中"scripts": [
"../node_modules/jspdf/dist/jspdf.min.js"
]
然后在组件中添加以下内容
import * as JSPdf from 'jspdf';
然后在你的班级
generatePdf() {
let doc = new JSPdf();
doc.text("Hello", 20, 20);
doc.save('table.pdf');
}