IvoPereira
1/8/2015 - 7:28 PM

Take screenshot, convert it to Canvas to be inserted into a PDF (support SVG)

Take screenshot, convert it to Canvas to be inserted into a PDF (support SVG)

    function take(targetElem) {
        // First render all SVGs to canvases
        var elements = targetElem.find('svg').map(function() {
            var svg = $(this);
            var canvas = $('<canvas></canvas>');
            svg.replaceWith(canvas);

            // Get the raw SVG string and curate it
            var content = svg.wrap('<p></p>').parent().html();
            content = content.replace(/xlink:title="hide\/show"/g, "");
            content = encodeURIComponent(content);
            svg.unwrap();

            // Create an image from the svg
            var image = new Image();
            image.src = 'data:image/svg+xml,' + content;
            image.onload = function() {
                canvas[0].width = image.width;
                canvas[0].height = image.height;

                // Render the image to the canvas
                var context = canvas[0].getContext('2d');
                context.drawImage(image, 0, 0);
            };
            return {
                svg: svg,
                canvas: canvas
            };
        });
        targetElem.imagesLoaded(function() {
            // At this point the container has no SVG, it only has HTML and Canvases.
            html2canvas(targetElem[0], {
                onrendered: function(canvas) {
                    // Put the SVGs back in place
                    elements.each(function() {
                        this.canvas.replaceWith(this.svg);
                    });

                    // Do something with the canvas, for example put it at the bottom
                 $(canvas).appendTo('body');
                }
            })
        })
    }

// (uses https://github.com/desandro/imagesloaded)