Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pdf kit save images from a url?

Tags:

node.js

pdfkit

I have a node.js application in which I'm using pdfkit to generate pdf documents. I want to be able to include images from a url in the pdf. I cant save the image to the file system because my runtime environment is read only and pdf kit seems to find the images to embed from a file system directory. Is there a way I can use an url in pdf kit to embed an image?


Here. This guy modified the pdfkit to include that functionality.

like image 834
jokham Avatar asked Apr 12 '12 05:04

jokham


2 Answers

PDFKit now supports passing buffers to the doc.image method instead of a filename. See this commit. So you could do as the other answer suggests, and download the image from the URL yourself, and then pass the buffer directly to PDFKit instead of saving it to a file first.

like image 85
devongovett Avatar answered Oct 14 '22 12:10

devongovett


you can use http.get:

    http.get('YOUR URL TO GET THE IMAGE').on('response', function(res)
    res.setEncoding('binary');
    res.on('data', function(chunk){
       buffer += chunk;
    });
    res.on('end', function(){

    fs.writeFile('PATH TO SAVE IMAGE', buffer, 'binary', function (err) {
        if (err){
           throw err;
        }
        doc = new PDFDocument({ size: 'LETTER or any other size pdfkit offer' });
        doc.image('PATH TO SAVE IMAGE', 0, 0, { fit: [WIDTH, HEIGHT] })
        .fontSize(10).text('text 1', 100, 170)
        .fontSize(16).text('text 2', 60, 120)

    }); //After file is download and was write into the HD will use it

}).end(); //EO Downloading the file
like image 23
Doron Segal Avatar answered Oct 14 '22 11:10

Doron Segal