score:14

Accepted answer

thanks to pawel fus for the nod in the right direction, we got this working using canvg.js, which temporarily replaces the svg with a canvas before calling html2canvas.

the final issue came when some of the html within the svg uses em's to size the font (which unfortunately a lot of our templates do). we got around this by updating the font size for anything using em's to the underlying pixel size before rendering the svg into a canvas (see get computed font size for dom element in js for how we calculated the actual font size)

below is the updated code for the download button click

$('#download').click(function() {
  var svgelements = $("#container").find('svg');

  //replace all svgs with a temp canvas
  svgelements.each(function() {
    var canvas, xml;

    // canvg doesn't cope very well with em font sizes so find the calculated size in pixels and replace it in the element.
    $.each($(this).find('[style*=em]'), function(index, el) {
      $(this).css('font-size', getstyle(el, 'font-size'));
    });

    canvas = document.createelement("canvas");
    canvas.classname = "screenshottempcanvas";
    //convert svg into a xml string
    xml = (new xmlserializer()).serializetostring(this);

    // removing the name space as ie throws an error
    xml = xml.replace(/xmlns=\"http:\/\/www\.w3\.org\/2000\/svg\"/, '');

    //draw the svg onto a canvas
    canvg(canvas, xml);
    $(canvas).insertafter(this);
    //hide the svg element
    $(this).attr('class', 'temphide');
    $(this).hide();
  });


  html2canvas($("#container"), {
    onrendered: function(canvas) {
      var imgdata = canvas.todataurl(
        'image/png');
      var doc = new jspdf('p', 'mm');
      doc.addimage(imgdata, 'png', 10, 10);
      doc.save('sample-file.pdf');
    }
  });

  $("#container").find('.screenshottempcanvas').remove();
  $("#container").find('.temphide').show().removeclass('temphide');
});

see an updated jsfiddle of it in action here - http://jsfiddle.net/zuvzcgvz/22/


Related Query

More Query from same tag