Search code examples
javascriptnode.jsbase64data-uri

How to read remote image to a base64 data url


actually there are many answers for this question. But my problem is, i want to generate pdf dynamically with 5 external(URL) images. Im using PDFmake node module. it supports only two ways local and base64 format. But i don't want to store images locally. so my requirement is one function which takes url as parameter and returns base64. so that i can store in global variable and create pdfs

thanks in advance

function urlToBase(URL){
return base64;
}

var img = urlToBase('https://unsplash.com/photos/MVx3Y17umaE');
var dd = {
            content: [
              {
                text: 'fjfajhal'
              },
              {
                image: img,
              }
            ]
          };

          var writeStream = fs.createWriteStream('myPdf.pdf');
        var pdfDoc = printer.createPdfKitDocument(dd);
        pdfDoc.pipe(writeStream);
        pdfDoc.end();

im using PDFmake module from npm


Solution

  • The contents of the remote image can first be fetched with an HTTP request, for example using the ubiquitous request npm module. The image string contents can then be transformed to a buffer and finally converted to a base64 string. To complete the transformation, add the proper data-url prefix, for example, data:image/png,base64, to the beginning of the base64 string.

    Here is a rough example for a PNG image:

    const request = require('request-promise-native');
    
    let jpgDataUrlPrefix = 'data:image/png;base64,';
    let imageUrl         = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';
    
    request({
        url: imageUrl,
        method: 'GET',
        encoding: null // This is actually important, or the image string will be encoded to the default encoding
    })
        .then(result => {
            let imageBuffer  = Buffer.from(result);
            let imageBase64  = imageBuffer.toString('base64');
            let imageDataUrl = jpgDataUrlPrefix+imageBase64;
    
            console.log(imageDataUrl);
        });