感谢 Pawel Fus 在正确的方向上的点头,我们使用 canvg.js 完成了这项工作,它在调用 html2canvas 之前暂时用画布替换了 svg。
当 svg 中的某些 html 使用 em 来调整字体大小时,最后一个问题就出现了(不幸的是,我们的许多模板都这样做)。我们通过在将 svg 渲染到画布之前将使用 em 的任何内容的字体大小更新为基础像素大小来解决这个问题(请参阅获取 JS 中 DOM 元素的计算字体大小 https://stackoverflow.com/questions/1955048/get-computed-font-size-for-dom-element-in-js了解我们如何计算实际字体大小)
以下是下载按钮单击的更新代码
$('#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');
});
在这里查看它的更新版 jsfiddle -http://jsfiddle.net/zuvzcgvz/22/ http://jsfiddle.net/zuvzcgvz/22/