我正在尝试创建一个PDF,其中的数据是从数据库中提取的。下面是我如何在TypeScript中做变量声明。
essay = {
"title": "",
"author": { "fullname": "" },
"intro": "",
"conclusion": "",
"paragraphs": [ { "paragraph": "" } ]
}正如您在这里看到的,段落是数组的类型。因此,当触发生成PDF的按钮时,将调用下面的函数。
CreatePdf(){
var docDefinition = {
content: [
{ text: this.essay.title, style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },
{ text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },
// Foreach essay.paragraphs and display the value
{ text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }
]
}
this.pdfObj = pdfMake.createPdf(docDefinition);
this.pdfObj.download();
}问题是,我将如何在content:[]中显示所有段落的值?我试图在内容中应用下面的循环,但做不到。
for(let parag of this.essay.paragraphs){
console.log(parag.paragraph);
};发布于 2018-06-18 07:32:44
您可以使用...运算符和map()来完成它。
CreatePdf(){
var docDefinition = {
content: [
{ text: this.essay.title, style: 'header' },
{ text: new Date().toTimeString(), alignment: 'right' },
{ text: 'Written By : '+this.essay.author.fullname, style: 'subheader' },
{ text: this.essay.intro, style: 'story', margin: [0, 20, 0, 20] },
...this.essasy.paragraphs.map( p => {
return {text: p.paragraph, style: 'story', margin: [0, 20, 0, 20]};
}),
{ text: this.essay.conclusion, style: 'story', margin: [0, 20, 0, 20] }
]
}
this.pdfObj = pdfMake.createPdf(docDefinition);
this.pdfObj.download();
}顾名思义,map()使用赋予它的函数映射每个元素,而...只是简单地扁平了一个数组。
https://stackoverflow.com/questions/50904395
复制相似问题