Using html2canvas to render a highcharts chart to pdf doesn't work on IE and Firefox

爷,独闯天下 提交于 2019-12-04 03:53:48
Rob

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/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!