0

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?

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

5 Comments

the snippet doesnt include the yellow bg of the div
Browser ignore background color by default. Adding the CSS body { -webkit-print-color-adjust: exact !important; } enables it for Chrome.
@ChanMT I never knew of this property. I've added it to the answer.
how do I include positioning as well? it works tho. thanks!
<style type="text/css" media="print"> this line did the trick into adding positioning to be included

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.