Images & PDFMake

Ed Wu picture Ed Wu · Jun 6, 2016 · Viewed 15.9k times · Source

I'm currently using pdfmake to generate project report pdf's given information, and I'm having some trouble getting images to display.

I have a function that generates a pdfmake "object" that goes like this:

function singleProject(data) {
    return {
        text: "Project: \n" + data.title + \n\nImage: \n",
        pageBreak: 'before'
    }
}

I want to add an image to that report given an image URL (something like "images/sample_image.jpg"), and from what I've read on other answers I have to convert it to a base 64 format.

One of these functions was provided in another answer but I can't quite figure out how I'm supposed to be utilizing it:

function convertImgToBase64URL(url, callback, outputFormat){
    var canvas = document.createElement('CANVAS'),
        ctx = canvas.getContext('2d'),
        img = new Image;
    img.crossOrigin = 'Anonymous';
    img.onload = function(){
        var dataURL;
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        dataURL = canvas.toDataURL(outputFormat);
        callback(dataURL);
        canvas = null;
    };
    img.src = url;
}

However, I'm not exactly too sure how I should go about using this function to add the image to the first function provided, as it doesn't return the dataURL; if I try something like:

function singleProject(data) {
    return {
        text: "Project: \n" + data.title + \n\nImage: \n",
        image: convertImgToBase64URL(data.image), //data.image is the URL so something like "images/sample_image.jpg"
        width: 300,
        pageBreak: 'before'
    }
}

The image doesn't show up.

Answer

Balajiprasad Ramesh picture Balajiprasad Ramesh · Jun 7, 2016

Use hidden

<img id='imgToExport' src='someimageurl' style='display:none'/> 

and in JavaScript use

var imgToExport = document.getElementById('imgToExport');
var canvas = document.createElement('canvas');
        canvas.width = imgToExport.width; 
        canvas.height = imgToExport.height; 
        canvas.getContext('2d').drawImage(imgToExport, 0, 0);
  canvas.toDataURL('image/png')

By this way you donot need asynchronous call