To print a div with the css style

Viewed 621

I made a script to print just a div, but when I see the preview, it doesn't "format" the page using the CSS added.

HTML Part:

<center>Do not print this</center>              
<div>Hi mom!</div>
<center>Print this</center>
<div id="content" class="print">Hi dad!</div>
            <input type='button' value='Print' onClick='Print()' />

JS part

function Print(){
     var corpo = document.getElementById('content').innerHTML;

     var a = window.open('','','width=640,height=480');
     a.document.open("text/html");
     a.document.write("<html><head><link rel=\"stylesheet\" href=\"./style.css\"></head><body><div class=\"print\">");
     a.document.write(corpo);
     a.document.write("</div></body></html>");
     a.document.close();
     a.print(); 
}

A live version: https://codepen.io/Pop1111/pen/Vwabbzd

It looks like it load the css only AFTER.

Any tips?

2 Answers

Your code will create invalid HTML

Try

function Print() {
  var corpo = document.getElementById('content').innerHTML;
  const html = [];
  html.push('<html><head>');
  // assuming the first stylesheet on the parent page - use a different selector if not
  // or use +location.protocol+'//'+location.host+'/style.css">'
  html.push('<link rel="stylesheet" href="' + document.querySelector("link[rel=stylesheet]").href + '">');
  html.push('</head><body onload="window.focus(); window.print()"><div>');
  html.push(corpo);
  html.push('</div></body></html>');
  console.log(html)
  /*  this will not work in the snippet - uncomment on your server
  var a = window.open('', '', 'width=640,height=480');
  a.document.open("text/html");
  a.document.write(html.join(""));
  a.document.close();
  */
}
<html>

<head>
  <link rel="stylesheet"  href="test.css" />
</head>

<body>
  <center>Do not print this</center>
  <div>Hi mom!</div>
  <center>Print this</center>
  <div id="content" class="print">Hi dad!</div>
  <input type='button' value='Print' onClick='Print()' />
</body>

</html>

Your new document is unsaved, so does not have your expected path, so the relative reference of the CSS file is not finding the CSS.

To get this to work as expected, you would need to change the CSS reference to absolute reference, or add code to save the new HTML file first.

Is this just how you have tested it, or will your production version function like this as well? (New file, not saved, then print).

You could always inject the actual CSS itself into the head of the new document between style tags, instead of just a reference to the CSS file. Try that.

Related