如何将图像从URL写入PDFkit?

时间:2017-09-14 15:18:06

标签: javascript node.js pdfkit node-pdfkit

我使用node.js请求从URL获取JPEG。 然后我将图像转换为base64缓冲区并将其写入pdf文档:

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)

3 个答案:

答案 0 :(得分: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();
    }
});

答案 1 :(得分:1)

JS 和 Axios 示例:

async function fetchImage(src) {
    const image = await axios
        .get(src, {
            responseType: 'arraybuffer'
        })
    return image.data;
}

const logo = await fetchImage("https://i.imgur.com/2ff9bM7.png");
doc.image(logo, 0, 200);

答案 2 :(得分:0)

TypeScriptnode-fetch示例:

const fetchImage = async (src: string) => {
  const response = await fetch(src);
  const image = await response.buffer();

  return image;
};
    
const logo = await fetchImage("https://i.imgur.com/2ff9bM7.png");
doc.image(logo, 0, 200);