2017-09-14 68 views
0

我使用node.js請求從URL獲取JPEG。 我然後將圖像轉換爲一個base64緩衝區,並將其寫入到PDF文檔:如何將圖像從URL寫入PDFkit?

request({ url: url, encoding: null }, function (error, response, body) { 
         if (!error && response.statusCode == 200) { 
          var img = new Buffer(body, 'base64'); 
          pdf.image(img, 0, 0); 
          callback(error, body); 
         } 
        }); 

我收到以下錯誤消息:

events.js:160 
     throw er; // Unhandled 'error' event 
    ^

Error: stream.push() after EOF 
    at readableAddChunk (_stream_readable.js:156:17) 
    at PDFDocument.Readable.push (_stream_readable.js:134:10) 
    at PDFDocument._write (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/document.js:156:12) 
    at PDFReference.finalize (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:81:21) 
    at PDFReference.finalize (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:10:59) 
    at PDFReference.end (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/reference.js:74:21) 
    at JPEG.embed (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/image/jpeg.js:68:16) 
    at PDFDocument.image (/Users/assafshamia/Freebird/node/utils/report_generator/node_modules/pdfkit/js/mixins/images.js:34:15) 
    at addImage (/Users/assafshamia/Freebird/node/utils/report_generator/dist/all.js:19:6) 
+0

難道pdf.end()是越來越提前叫什麼名字? –

回答

1

你的代碼看起來對我罰款。
然而,這裏是100%的工作片段:

request({ url, encoding: null }, (error, response, body) => { 

    if (!error && response.statusCode === 200) { 
     pdf.pipe(fs.createWriteStream('out.pdf')); 

     var img = new Buffer(body, 'base64'); 
     pdf.image(img, 0, 0); 

     pdf.end(); 
    } 
});