Media query print doesn't work by javascript command

Viewed 1829

I'm building a html report using media query print. Up to this point everything was working well, until I added a "Print" button to the page that performs the JavaScript command "window.print()". By using the shortcut (Ctrl + P) my web browser shows the print preview according to the media print, however, when I click on the "Print" button, the media query rules is been ignored.

Does anyone now how to fix it?

@media print {

  @page { 
    size: A4; 
    margin: 1cm
  }

  body * {
    visibility: hidden;
  }

  .printArea, .printArea * {
    visibility: visible;
  }

  .spacePrint{
    border: 1px solid #ccc;
  }

  .printArea {
    margin-top :0;
    position: fixed;
    left: 0;
    top: 0px;
  }
}
2 Answers

This can be fixed by waiting for the event queue to clear before calling window.print(). This code worked for me:

setTimeout(() => window.print(), 0);
Related