第一步:把对应 dom 节点里所有的 svg 元素替换成 canvas
第二步:把 glyphicons 字体转成 canvas。如果项目中没有用到 glyphicons 字体图标,可忽略这一步
- 1 glyphicons2canvas: function(targetElem, fontClassName, fontFamilyName) {
- 2
- var iconElems = targetElem.find('.' + fontClassName);
- 3 iconElems.each(function(index, inconNode) {
- 4
- var fontSize = $(inconNode).CSS("font-size");
- 5
- var iconColor = $(inconNode).css("color");
- 6
- var styleContent = $(inconNode).attr('style');
- 7 //去掉"px"
- 8 fontSize = fontSize.replace("px", "");
- 9
- var charCode = getCharCodeByGlyphiconsName(iconName);
- 10
- var myCanvas = document.createElement('canvas');
- 11 //把canva宽高各增加2是为了显示图标完整
- 12 myCanvas.width = parseInt(fontSize) + 2;
- 13 myCanvas.height = parseInt(fontSize) + 2;
- 14 myCanvas.style = styleContent;
- 15
- var ctx = myCanvas.getContext('2d');
- 16 //设置绘图内容的颜色
- 17 ctx.fillStyle = iconColor;
- 18 //设置绘图的字体大小以及font-family的名字
- 19 ctx.font = fontSize + 'px ' + fontFamilyName;
- 20 ctx.fillText(String.fromCharCode(charCode), 1, parseInt(fontSize) + 1);
- 21 $(inconNode).replaceWith(myCanvas);
- 22
- });
- 23
- }
- 24 //根据glyphicons/glyphicon图标的类名获取到对应的char code
- 25 getCharCodeByGlyphiconsName: function(iconName) {
- 26
- switch (iconName) {
- 27
- case("glyphicons-resize-full"):
- 28
- return "0xE216";
- 29
- case("glyphicons-chevron-left"):
- 30
- return "0xE225";
- 31
- default:
- 32
- return "";
- 33
- }
- 34
- }
第三步:html 转 canvas 转图片再转 pdf
- 1 html2canvas($("#myExportArea"), {
- 2 onrendered: function(canvas) {
- 3
- var imgData = canvas.toDataURL('image/jpeg');
- 4
- var img = new Image();
- 5 img.src = imgData;
- 6 //根据图片的尺寸设置pdf的规格,要在图片加载成功时执行,之所以要*0.225是因为比例问题
- 7 img.onload = function() {
- 8 //此处需要注意,pdf横置和竖置两个属性,需要根据宽高的比例来调整,不然会出现显示不完全的问题
- 9
- if (this.width > this.height) {
- 10
- var doc = new jsPDF('l', 'mm', [this.width * 0.225, this.height * 0.225]);
- 11
- } else {
- 12
- var doc = new jsPDF('p', 'mm', [this.width * 0.225, this.height * 0.225]);
- 13
- }
- 14 doc.addImage(imgData, 'jpeg', 0, 0, this.width * 0.225, this.height * 0.225);
- 15 //根据下载保存成不同的文件名
- 16 doc.save('report_pdf_' + new Date().getTime() + '.pdf');
- 17
- }
- 18
- },
- 19 background: "#fff",
- 20 //这里给生成的图片默认背景,不然的话,如果你的html根节点没设置背景的话,会用黑色填充。
- 21 allowTaint: true //避免一些不识别的图片干扰,默认为false,遇到不识别的图片干扰则会停止处理html2canvas
- 22
- });
虽然最后勉强完成了客户的要求,但是生成的 pdf 效果明显不如正常截图来的清晰…… 水平所限,暂时只能想到这种方法,如果大家有更好的办法,欢迎指点。
来源: http://www.cnblogs.com/skyInk/p/6401563.html