保存来自NodeJS服务器的缓冲区/流 [英] Saving buffer/stream that comes from nodejs server
本文介绍了保存来自NodeJS服务器的缓冲区/流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定我做错了什么。
我有一个html内容,并希望将其另存为pdf。我使用html-pdf(来自NPM)和一个下载库http://danml.com/download.html
实际上,当我直接保存到文件或将其显示为结果时,我可以毫不费力地获得pdf。但是我从js方法调用了我的WebService方法,并且我有一个流/缓冲区作为返回值,并保存在‘Download’库中以下是我的代码
pdf.create(html, options).toFile('./mypdf.pdf', function (err, res) {
if (err) return console.log(err);
console.log(res);
});
pdf.create(html,options).toBuffer(function (err, buffer) {
if (err) return reject(err);
return resolve(buffer);
});
//res.setHeader('Content-type', 'application/pdf');
pdf.create(html, options).toStream(function (err, stream) {
if (err) return res.send(err);
//res.type('pdf');
return resolve(stream);// .pipe(res);
});
我可以将内容保存为pdf,它工作得很好。但当我尝试发送流或缓冲区时,不知何故页面是空的。我用记事本打开了这两个pdf文件。这里有一些不同之处。例如,有问题的一个是44kb,另一个是78kb。并且空的那个还包含以下行
%PDF-1.4 1 0 Obj<;<;/标题(��)/创建者(��)/制片人(��Q t 5. 5.1)/创建日期(D:20190524152156)
endobj
我认为toBuffer或toStream方法在我的例子中有问题。因为溪流看起来还不错。至少我可以看到这是一个pdf文件(没有错误,只是页面是空的)
不管怎样,这是我的API路由器
let result = await
routerVoucher.CreatePdfStream(req.query.VoucherCode,req.query.AppName);
res.setHeader('Content-type', 'application/pdf');
res.type('pdf');
//result.pipe(res);
res.end(result, 'binary');
这是我的js客户
$.ajax({
type: "GET",
url: '/api/vouchers/GetLicensePdf',
data:data,
success: function (pdfFile) {
if (!pdfFile)
throw new Error('There is nothing to download');
download(pdfFile,voucherCode + '.pdf', 'application/pdf')
推荐答案
我已解决问题。
首先我将缓冲区转换为Base64
const base64 = buffer.toString('base64')
然后使用以下代码将Base64转换为BLOB
function base64toBlob (base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
//var byteCharacters = decodeURIComponent(escape(window.atob(base64Data)))
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
然后
我再次使用了我的下载方法(从download.js库),如下所示
download(new Blob([base64toBlob(base64PDF,"application/pdf")]),
voucherCode + '.pdf', "application/pdf");
那么一切都很好:)
这篇关于保存来自NodeJS服务器的缓冲区/流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文