There are plenty of examples for printing html of an element. Most of them look like this
123456789101112
//The simple soultion but has few problems listed below.functionprintHtml(html){varmywindow=window.open();mywindow.document.write('<html><head><title>My App</title>');mywindow.document.write('</head><body>');mywindow.document.write(html);mywindow.document.write('</body></html>');mywindow.print();mywindow.close();returntrue;}
The issues with above solution:
The new window pop up would be blocked by browsers. Users need to enable pop up.
If you have external css files, you will notice the styling not applied some times.
If you have images(like logo), the print will be missing these images intermittently.
The first issue can be addressed by using an iframe instead of new window. The 2nd and 3rd issues are addressed by making sure print happens after page has loaded css files and images. The working solution we use in Bahmni for printing patient registration cards looks like this
12345678910111213141516
varprintHtml=function(html){varhiddenFrame=$('<iframe style="display: none"></iframe>').appendTo('body')[0];hiddenFrame.contentWindow.printAndRemove=function(){hiddenFrame.contentWindow.print();$(hiddenFrame).remove();};varhtmlDocument="<!doctype html>"+"<html>"+'<body onload="printAndRemove();">'+// Print only after document is loadedhtml+'</body>'+"</html>";vardoc=hiddenFrame.contentWindow.document.open("text/html","replace");doc.write(htmlDocument);doc.close();};
For printing contents of an element you can use this
12345
//element can be found by document.querySelectorAll(slector)[0]//or using jQuery(selector)[0]varprintElement=function(element){printHtml(element.innerHTML)};