使用 PDFKit 遍历数据并生成页面
Iterating through data and generate pages with PDFKit
我想使用 for 循环在 pdfkit 中生成页面。在我的应用程序中,我创建了一个根据请求加载的新模块(所有这些都工作正常,我可以在没有循环的情况下创建pdf)。使用循环pdfkit创建一个pdf,但是这个被破坏了。
模块中的代码:
module.exports = function () {
var Project = require('./models/projects');
var PDFDocument = require('pdfkit');
var doc = new PDFDocument;
doc.fontSize(25);
doc.text('Portfolio');
Project
.find()
.exec(function (err, projects) {
if (err) {
console.log(err);
} else {
projects.forEach(function (project) {
var project_customer = project.customer;
doc.addPage();
doc.text('project_customer');
});
}
});
doc.addPage();
doc.text('project_customer');
doc.save();
doc.write('./output.pdf');
}
有没有解决方案如何获得未损坏的pdf?
在代码中,Project.find().exec(...)
异步运行。这意味着您正在创建 PDF 文档并在调用完成之前保存Project.find().exec(...)
。
我建议将PDF代码移动到exec()
中包含的回调中,如下所示:
module.exports = function () {
var Project = require('./models/projects');
var PDFDocument = require('pdfkit');
Project
.find()
.exec(function (err, projects) {
if (err) return console.log(err);
var doc = new PDFDocument;
doc.fontSize(25);
doc.text('Portfolio');
projects.forEach(function (project) {
var project_customer = project.customer;
doc.addPage();
doc.text('project_customer');
});
doc.addPage();
doc.text('project_customer');
doc.save();
doc.write('./output.pdf');
});
}
相关文章:
- 循环遍历以数组为值的Javascript对象
- 遍历类元素数组,并在jquery中选择同级元素
- Jquery遍历表元素
- Chrome扩展:遍历不同的页面并收集数据
- 如何遍历包含对象的数组-javascript
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 遍历AngularJs中的对象
- JQuery 遍历当前 SELECT 值
- 循环遍历包含另一个表单的表单
- 使用Yadda和Protractor重用步骤定义,遍历所需文件
- 遍历D3中所有数据点之间的所有值
- 自动遍历所有链接的事件
- JS.循环遍历多维数组,以计数元素在每列中的出现次数
- 如何使用 document.querySelectorAll 遍历选定的元素
- 使用Javascript反向遍历XML
- 当知道同一hiearch中至少有一个元素时,遍历到元素.结构使用jquery
- Netsuite Suitelet:在不达到治理限制的情况下,遍历事务行项目的列表加载和提交记录
- 遍历DOM查找字符串有时会正确返回
- 如何使用SnapSVG将SVG作为树结构遍历
- 在Javascript中递归遍历树