naeemqaswar
3/31/2017 - 11:13 AM

Print HTML Element with Javascript

Print HTML Element with Javascript

print_html_ele('.my_div'); // Function call

function print_html_ele(element) {
  
    var contents = $(element).html();
    var frame1 = $('<iframe />');
    
    var css_link1 = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css';
    var css_link2 = '/css/style.css';
    
    frame1[0].name = "frame1";
    frame1.css({ "position": "absolute", "top": "-1000000px" });
    $("body").append(frame1);
    var frameDoc = frame1[0].contentWindow ? frame1[0].contentWindow : frame1[0].contentDocument.document ? frame1[0].contentDocument.document : frame1[0].contentDocument;
    frameDoc.document.open();
    //Create a new HTML document.
    frameDoc.document.write('<html><head>');
    frameDoc.document.write('</head><body>');
    //Append the external CSS file.
    frameDoc.document.write('<link href="'+css_link1+'" rel="stylesheet" type="text/css" />');
    frameDoc.document.write('<link href="'+css_link2+'" rel="stylesheet" type="text/css" />');
    //Append the DIV contents.
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        window.frames["frame1"].print();
        frame1.remove();
    }, 500);
}