During project development, we occasionally or often encounter some problems. Converting html pages to pdf using js is also a problem, which means that it is equivalent to cutting off the entire page and then saving it as pdf.
In fact, there are many ways to convert html to pdf, probably the following:
1. Most browsers have this function. However, this is not what our customers want. What they want is the export to pdf function that can be actively triggered in the system, so this solution is passed.
2. Use third-party tools. I found a solution using a tool like wkhtmltopdf to export. I tried it in our project, but the effect was not good, and the support for svg images was not good either. pass.
3. Another method is to use the iText class to generate java files in the background. But because the page that needs to be exported is a dynamic page, and if you directly pass the page to the backend, a lot of styles will be lost, so I still pass.
In the end, there is no good solution. I can only settle for the second best, thinking about converting the html page into a picture first, and then exporting the picture to pdf. Because it is necessary to support users to export and download, and to retain the style, it is best to implement a pure js front-end.
If you want to convert html to canvas, use html2canvas js. There are many introductions to this online, so I won’t go into nonsense here.
The more troublesome thing is the svg image. Directly using html2canvas cannot convert the content of the svg tag into canvas. After checking the information, I locked the js canvg. canvg is a Google plug-in that can convert svg tag content into canvas. Specific to our project, another difficulty is how to convert font icons such as glyphicons into canvas, because the support for this font icon is completely different in different browsers. The last method I found was to replace these font icons with char code and redraw them into canvas. There is no need to talk nonsense when generating images from canvas. Generating pdf from pictures is implemented using jsPDF. After struggling for a long time, I finally got the whole process through, and then posted the code step by step.
The first step: Replace all svg elements in the corresponding dom node with canvas
svg2canvas: function(targetElem) { var svgElem = targetElem.find('svg'); svgElem.each(function(index, node) { var parentNode = node.parentNode; //由于现在的IE不支持直接对svg标签node取内容,所以需要在当前标签外面套一层div,通过外层div的innerHTML属性来获取 var tempNode = document.createElement('div'); tempNode.appendChild(node); var svg = tempNode.innerHTML; var canvas = document.createElement('canvas'); //转换 canvg(canvas, svg); parentNode.appendChild(canvas); }); }
The second step: Convert the glyphicons font to canvas. If the glyphicons font icon is not used in the project, you can ignore this step
glyphicons2canvas: function(targetElem, fontClassName, fontFamilyName) { var iconElems = targetElem.find('.' + fontClassName); iconElems.each(function(index, inconNode) { var fontSize = $(inconNode).css("font-size"); var iconColor = $(inconNode).css("color"); var styleContent = $(inconNode).attr('style'); //去掉"px" fontSize = fontSize.replace("px", ""); var charCode = getCharCodeByGlyphiconsName(iconName); var myCanvas = document.createElement('canvas'); //把canva宽高各增加2是为了显示图标完整 myCanvas.width = parseInt(fontSize) + 2; myCanvas.height = parseInt(fontSize) + 2; myCanvas.style = styleContent; var ctx = myCanvas.getContext('2d'); //设置绘图内容的颜色 ctx.fillStyle = iconColor; //设置绘图的字体大小以及font-family的名字 ctx.font = fontSize + 'px ' + fontFamilyName; ctx.fillText(String.fromCharCode(charCode), 1, parseInt(fontSize) + 1); $(inconNode).replaceWith(myCanvas); }); } //根据glyphicons/glyphicon图标的类名获取到对应的char code getCharCodeByGlyphiconsName: function(iconName) { switch (iconName) { case("glyphicons-resize-full"): return "0xE216"; case ("glyphicons-chevron-left"): return "0xE225"; default: return ""; } }
Step 3: Convert html to canvas, convert image to pdf.
html2canvas($("#myExportArea"), { onrendered: function(canvas) { var imgData = canvas.toDataURL('image/jpeg'); var img = new Image(); img.src = imgData; //根据图片的尺寸设置pdf的规格,要在图片加载成功时执行,之所以要*0.225是因为比例问题 img.onload = function() { //此处需要注意,pdf横置和竖置两个属性,需要根据宽高的比例来调整,不然会出现显示不完全的问题 if (this.width > this.height) { var doc = new jsPDF('l', 'mm', [this.width * 0.225, this.height * 0.225]); } else { var doc = new jsPDF('p', 'mm', [this.width * 0.225, this.height * 0.225]); } doc.addImage(imgData, 'jpeg', 0, 0, this.width * 0.225, this.height * 0.225); //根据下载保存成不同的文件名 doc.save('report_pdf_' + new Date().getTime() + '.pdf'); } }, background: "#fff", //这里给生成的图片默认背景,不然的话,如果你的html根节点没设置背景的话,会用黑色填充。 allowTaint: true //避免一些不识别的图片干扰,默认为false,遇到不识别的图片干扰则会停止处理html2canvas });
Although this method can convert html pages into pdf format, the generated pdf effect is obviously not as clear as a normal screenshot. If you have a better way, please give us some advice.
Related recommendations:
C#How to convert HTML to images or PDF?
A summary of how to convert Word to PDF in C
#Use HTML to generate a PDF example code
The above is the detailed content of js to convert html to pdf. For more information, please follow other related articles on the PHP Chinese website!