Can pdf kit save images from a url?
Asked Answered
P

2

7

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.

Payne answered 12/4, 2012 at 5:10 Comment(5)
Nope, that's not possible with the current implementation. But I can tell you it's easy to modify the source and implement this feature.Howlet
I assume this question is about this pdfkitHowlet
This is where it reads the file. You can for example change it to @contents = filename or anything you want it to be.Howlet
@alFReDNSH one might even argue that would be a cleaner interface.Landloper
Is it possible through the pdfkit available through node without editing?Laurentian
A
3

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.

Antic answered 18/1, 2014 at 21:37 Comment(0)
H
1

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
Hyposthenia answered 22/11, 2013 at 18:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.