This time I will bring you how to use js to convert html to pdf, and how to use js to convert html to pdf. What are the precautions? The following is a practical case, let's take a look.
So I made a small case to test this function.<body> <!-- PDF --> <p class="bb" id="ctn"> <p class="anliu" id="anliu">生成PDF</p> </p></body><script src="../../Scripts/aps/html2canvas.js"></script><script src="../../Scripts/aps/jsPdf.debug.js"></script>
window.onload =function(){var downPdf = document.getElementById("anliu"); downPdf.onclick = function() { html2canvas(document.body, { onrendered: function(canvas) { //返回图片URL,参数:图片格式和清晰度(0-1) var pageData = canvas.toDataURL('image/jpeg', 1.0); //方向默认竖直,尺寸ponits,格式a4【595.28,841.89] var pdf = new jsPDF('', 'pt', 'a4'); //需要dataUrl格式 pdf.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28/canvas.width * canvas.height ); pdf.save('tup.pdf'); } }); } }
2, the problem of incomplete screenshots of html2canvas.js
When I put the function implemented by this test into the project, I encountered a new problem. The generated pdf only had pages. The visible area of the window and the area below the scroll bar are not generated. So I searched again and found that html2canvas does not support the height of the image captured. It will only be able to capture what is visible to the browser. If a scroll bar appears, the entire image will not be captured, so the pdf generated by jsPdf.js based on the screenshot will be generated. An incomplete problem occurs. Since it is caused by html2canvas screenshot, let’s solve it from here. After reading the cases written by others online, combined with my own testing + analysis, I found that if the interception is at the level of the body, and the body happens to be set to So I changed the style of the scroll bar node to height: auto; to let the height be stretched by the child elements. Go up and remove all parent nodes: overflow: hidden; remove the element from being visible. Look at the js rewritten in the project after introducing jqueryvar pdfcc = $('.pdf-cc'); pdfcc.on('click', function (event) { html2canvas($("#bb-pdf-ctn"), { allowTaint: true, height: $("#bb-pdf-ctn").outerHeight(), onrendered: function (canvas) { //返回图片URL,参数:图片格式和清晰度(0-1) var pageData = canvas.toDataURL('image/jpeg', 1.0); //方向默认竖直,尺寸ponits,格式a4【595.28,841.89] var pdf = new jsPDF('', 'pt', 'a4'); //需要dataUrl格式 pdf.addImage(pageData, 'JPEG', 0, 0, 595.28, 592.28 / canvas.width * canvas.height); pdf.save('pdf.pdf'); } }); });
How text-align achieves alignment at both ends
Inheritance and prototype chain of JavaScript
The above is the detailed content of Use js to convert html to pdf. For more information, please follow other related articles on the PHP Chinese website!