Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print function only works after second click

Tags:

javascript

I have this function to print a DIV.
Whenever the page is loaded and I click in a "Print" link I have, the DIV is shown to be printed without CSS.
If I close Chrome's print visualization page and click in the "Print" link again, the DIV has CSS applied.

Any ideas why?

Javascript

function printDiv(divId) {

  var printDivCSSpre =
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">' +
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/dist/css/sb-admin-2.css" rel="stylesheet">' +
'<div style="width:1000px; padding-right:20px;">';

  var printDivCSSpost = '</div>';

  $('body').append('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');

    $("link").clone().appendTo($("#print_frame").contents().find("head"));
window.frames["print_frame"].document.body.innerHTML =
    printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
  window.frames["print_frame"].window.focus();
  var windowInstance = window.frames["print_frame"].window;
  windowInstance.print();
}

HTML

<a id="print" href="#">
    <i class="fa fa-print"></i> Print
</a>
<script>
    $('#print').click(function () {
        printDiv('report')
    })
</script>

<div id="report" class="report">
    <p># Generated Table#</p>
</div>

First click:

http://imgur.com/a/Go81Y

Closing the print preview page and clicking again in print

http://imgur.com/a/SCxJF

like image 623
Ev. Avatar asked Feb 06 '17 13:02

Ev.


1 Answers

This happens because when you call your printDiv() function, css is also written using inner HTML and in this scenario CSS is not applied during first click because you wrote CSS to the elements even when they do not exist inside DIV.

The function to work as desired has to write DIV contents first and then CSS should be applied. I would say write css after contents of DIV or load on top of your HTML page and just write DIV contents.

Hope that helps.

like image 102
Atul Jindal Avatar answered Sep 30 '22 19:09

Atul Jindal