Reub
Reub

Reputation: 121

print div html code with css

I have this html code

function printDiv(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}
<div class="container">
  <div class="row">
    <div class="col s6 l6">
      <div class="center" id="div_id" style="height: 400px;width: 600px; position:relative; background-color: #ff0;">
        <img class="responsive-img" id="profile" width="200" src="https://picsum.photos/200">
      </div>
    </div>


    <div class="col s6 l6">
      <div class="card-panel" id="first_name">
        <span class="black-text"></span>
      </div>
      <a class="waves-effect waves-light btn" id="print" onclick="printDiv('div_id')">PRINT</a>
    </div>
  </div>
</div>

what I want is to print the div tag that contains the image with the css format or at least the position. is there anyway to do that?

Upvotes: 0

Views: 724

Answers (1)

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

The javascript is printing the innerHTML of the div (the img only). By changing the printContents variable to outerHTML you also get the div with its styling:

var printContents = document.getElementById(divName).outerHTML;

function printDiv(divName) {
  var printContents = document.getElementById(divName).outerHTML;
  var originalContents = document.body.innerHTML;

  document.body.innerHTML = printContents;

  window.print();

  document.body.innerHTML = originalContents;
}
body { -webkit-print-color-adjust: exact !important; }
<div class="container">
  <div class="row">
    <div class="col s6 l6">
      <div class="center" id="div_id" style="height: 400px;width: 600px; position:relative; background-color: #ff0;">
        <img class="responsive-img" id="profile" width="200" src="https://picsum.photos/200">
      </div>
    </div>


    <div class="col s6 l6">
      <div class="card-panel" id="first_name">
        <span class="black-text"></span>
      </div>
      <a class="waves-effect waves-light btn" id="print" onclick="printDiv('div_id')">PRINT</a>
    </div>
  </div>
</div>

Upvotes: 2

Related Questions