简体   繁体   English

保存来自nodejs服务器的缓冲区/流

[英]Saving buffer/stream that comes from nodejs server

I am not sure what I am doing wrong. 我不确定我做错了什么。

I have a html content and want to save it as pdf. 我有一个HTML内容,并希望将其保存为pdf。 I use html-pdf (from npm) and a download library http://danml.com/download.html 我使用html-pdf(来自npm)和下载库http://danml.com/download.html

Actually when I directly save to file or show it as a result I can get the pdf without problem. 实际上,当我直接保存到文件或显示它时,我可以毫无问题地获得pdf。 But I call my webservice method from a js method and I have a stream/buffer as a return value and saving with the 'download' library 但我从一个js方法调用我的webservice方法,我有一个流/缓冲区作为返回值并保存与'下载'库

Here is my code 这是我的代码

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);
 });

I can save the content as a pdf it works fine. 我可以将内容保存为pdf,它可以正常工作。 but when I try to send stream or buffer, somehow the page is empty. 但是当我尝试发送流或缓冲区时,页面显示为空。 I opened the both pdf files with notepad. 我用记事本打开了两个pdf文件。 There are some differences. 有一些差异。 For example, probless one is 44kb the other one 78 kb. 例如,问题一个是44kb,另一个是78kb。 and the empty one contains also the following lines 空的也包含以下行

%PDF-1.4 1 0 obj << /Title ( ) /Creator ( ) /Producer ( Q t 5 . 5 . 1) /CreationDate (D:20190524152156) %PDF-1.4 1 0 obj << / Title( )/ Creator( )/ Producer( Q t.5.5.1)/ CreationDate(D:20190524152156)

endobj endobj

I think toBuffer or toStream method has a problem in my case. 我认为toBuffer或toStream方法在我的情况下有问题。 Because the stream seems not bad. 因为流似乎不错。 at least I can see that it is a pdf file (no error, just page is empty) 至少我可以看到它是一个pdf文件(没有错误,只是页面是空的)

Anyway, here is my API router 无论如何,这是我的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');

and here is my js consumer 这是我的消费者

    $.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')

I've solved the problem. 我已经解决了这个问题。

Firstly I converted buffer to base64 首先我将缓冲区转换为base64

const base64 = buffer.toString('base64')

and then converted base64 to blob by using the following code 然后使用以下代码将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 });
}

and then 接着

again I've used my download method (from download.js library) as follow 我再次使用了我的下载方法(来自download.js库),如下所示

download(new Blob([base64toBlob(base64PDF,"application/pdf")]),
         voucherCode + '.pdf', "application/pdf");

then everything is fine :) 那一切都很好:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM