我使用pdfmake在nodejs中生成pdf并将数据发送到我的角度请求页面。我可以生成pdf。但我的问题是当我下载pdf时,它的名字看起来像“16064905-c4aa-4d40-96db-ca7464c38858.pdf”。我可以将自定义名称设置为我的.pdf文件吗?
这是我的代码
pdfHandler.createPdfBinary(courseDetail, function(binary) {
res.header('content-type', 'application/pdf');
res.send(binary);
}, function(error) {
res.send('ERROR:' + error);
});
exports.createPdfBinary = function(courseDetail,callback) {
var docDefinition = {...};
var pdfDoc = printer.createPdfKitDocument(docDefinition);
var chunks = [];
var result;
pdfDoc.on('data', function(chunk) {
chunks.push(chunk);
});
pdfDoc.on('end', function() {
result = Buffer.concat(chunks);
callback(result);
});
pdfDoc.end();
}
答案 0 :(得分:1)
在pdfDoc.on('end', function()
callback(null, result.toString('base64'));
当您收到回调结果时,请添加以下代码并将结果传递给方法
回调结果中的
b64toBlob(result, 'application/pdf');
文件下载方法
function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, {
type: contentType
});
if (blob) {
saveAs(blob, 'your_file_name.pdf'); /// TODO change with your filename
} else {
throw 'Could not generate blob';
}
}
您需要在代码中添加一个包 FileSaver
有关更多详细信息,请查看我的GitHub示例 https://github.com/daupawar/MeteorAsyncPdfmake
答案 1 :(得分:0)
我会做得更精简一点。 Btw Content-Disposition可用于设置文件的自定义名称
let fileName = 'sample.pdf'
let stream = pdfHandler.createPdfBinary(courseDetail)
res.header('Content-Type', 'application/pdf')
res.header('Content-Disposition', 'attachment; filename=' + fileName)
stream.pipe(res)
// instead of buffering all chunks and concatenating everything
// we simply just return the stream, so no callback is necessary
// ...this is also better for memory
exports.createPdfBinary = courseDetail => {
var docDefinition = {...}
return printer.createPdfKitDocument(docDefinition)
}