我在Nodejs上使用了这个模块:https://github.com/bpampuch/pdfmake
以下是我创建它的代码:
const fonts = {
Roboto: {
normal: './fonts/Roboto-Regular.ttf',
bold: './fonts/Roboto-Medium.ttf',
italics: './fonts/Roboto-Italic.ttf',
bolditalics: './fonts/Roboto-Italic.ttf'
}
};
let PdfPrinter = require('pdfmake/src/printer');
let printer = new PdfPrinter(fonts);
let fs = require('fs');
module.exports.generateFile = function (data,callback) {
let fileName = "Logins_" + data[0]["userLogin"] + ".pdf";
let filePath = __dirname + "/files/" + fileName;
let logins = [ ['userLogin', 'softwarePassword', 'softwareName'] ];
for (let obj of data) {
let arr = [];
for(let x in obj){
arr.push(obj[x]);
}
logins.push(arr);
}
let docDefinition = {
content: [
{
table: {
// headers are automatically repeated if the table spans over multiple pages
// you can declare how many rows should be treated as headers
headerRows: 1,
widths: [ '*', 'auto', 100, '*' ],
body: logins
}
}
]
};
try {
let chunks = [];
let result;
let doc = printer.createPdfKitDocument(docDefinition);
doc.pipe(fs.createWriteStream(filePath));
doc.end();
callback(null,fileName,filePath)
} catch (err){
callback(err);
}
};
我有这个屏幕:
任何想法的家伙? 在回调中,我使用带有文件名和文件路径的res.download。 我尝试了一切
答案 0 :(得分:2)
在本地和节点服务器上测试工作解决方案
为什么pdf无法打开文件是因为文件流“fs”仍在写入内存块。这使得它无法读取,下载的pdf将被破坏,大小为0KB。
解决方案:向fs.createWriteSteam添加一个事件监听器并等待fs完成写入然后发送文件
pdfDoc.pipe(temp123 = fs.createWriteStream('./PDF/' + name), { encoding:'utf16' });
pdfDoc.end();
temp123.on('finish', async function () {
// do send PDF file
});`