user3733831
user3733831

Reputation: 2926

External CSS not loading in window.print()

I am trying to print a specific content area of my page. My problem is I have created separate CSS file for the content of this print area. But that external CSS is not working (loading) in browser print popup. I am sure file path is correct.

This is how I tried it:

function printReceipt(el) {
  var docHead = "<html>\
                  <head>\
                    <title></title>\
                    <link rel='stylesheet' href='css/receipt-print.css' type='text/css' media='print' />\
                  </head>\
                  <body>";
  var docFoot = " </body>\
                 </html>";
  var docBody     = document.getElementById(el).innerHTML;
  var defaultBody = document.body.innerHTML;
  document.body.innerHTML = docHead+docBody+docFoot;
  //document.close(); 
  //window.focus(); 
  //setTimeout(function() {
  window.print();
  document.body.innerHTML = defaultBody;
  //}, 1000);    
  //return true;
}

UPDATE:

Also check in this way. Problem is sill same.

function printReceipt(el) {
  var w = window.open();
  w.document.write('<html><head><title></title>');
  w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
  w.document.write('</head><body >');
  w.document.write(document.getElementById(el).innerHTML);
  w.document.write('</body></html>');

  w.document.close();
  w.focus();
  w.print();
  w.close();
  return true;
}

Any ideas and suggestion would be appreciated.

Upvotes: 6

Views: 7163

Answers (1)

a.mola
a.mola

Reputation: 4011

The issue was you were printing the page without waiting for the styles and resources to load.

You should wait for the page to load before trying to print it or you can try using inline styles.

function printReceipt(el) {
  var w = window.open();

  w.document.write('<html><head><title></title>');
  w.document.write('<link rel="stylesheet" type="text/css" href="css/receipt-print.css">');
  w.document.write('</head><body >');
  w.document.write(document.getElementById(el).innerHTML);
  w.document.write('<script type="text/javascript">addEventListener("load", () => { print(); close(); })</script></body></html>');

  w.document.close();
  w.focus();
}

Upvotes: 5

Related Questions