var make_pdf = function ($elements, margin) {
    var content = [],
        count = 0;
        docDefinition = {content: content};

    for (i = $elements.length - 1; i >= 0; i--) {
        makeCanvas(i); 
    } 

    function makeCanvas(idx) {
        count += 1;
        html2canvas($elements[idx], {
            onrendered: function(canvas) {

                var data = canvas.toDataURL();
                content[idx] = {
                    image:data, 
                    width:520,
                    margin: margin
                };
                count -= 1;
                if (count === 0) {
                    //pdfMake.createPdf(docDefinition).download(title + '.pdf');
                    pdfMake.createPdf(docDefinition).getDataUrl(function(dataUrl) {
                        var pdfFile = dataUrl;
                        return pdfFile;
                    });
                }
            }
        })
    }
}