Home > database >  Printing only a div from an HTML domain in specific dimensions
Printing only a div from an HTML domain in specific dimensions

Time:01-16

I'm trying to find a way to print only a div from a web domain with specific dimensions (3"x5"). I set up the print button but so far every time I print the whole page comes out.

Is there anyway to hide all the non-div content on print preview?

CSS

.wholebody {
  height: 289px;
  width: 489px;
  border: 2px solid #00001a;
}

</style>

HTML

<body>


<button onclick="window.print()">Print Page</button>


<div >

</div>

Let me know if I should (and what kind of) JS functions would enable me to hide the non-div content. Thanks.

CodePudding user response:

You could use the css @media type print to select which content you want to print.

print Intended for paged material and documents viewed on a screen in print preview mode. (Please see paged media for information about formatting issues that are specific to these formats.)

.wholebody {
  height: 289px;
  width: 489px;
  border: 2px solid #00001a;
}

@media print{
body{
visibility: hidden;
}
div{
visibility: visible; 
}

}
<button onclick="window.print()">Print Page</button>

<p>Not printing this</p>
<div >Print this</div>

CodePudding user response:

You can write the styles you want to appear when the web page opens in the @media screen{} block. When the window.print() method is executed, the styles inside the @media print{} block are applied. In this example, clicking the <button> element will transfer the created element to the authoring page.

var button = document.getElementById('printButton');

printButton.addEventListener('click', function(){  
  var div = `<div style="width:30px;height:50px;border:2px solid black; margin: 20px; display: block;"></div>`;
  $('.wholebody').append(div);
   window.print();
});
@media screen{
  .wholebody {
    height: 289px;
    width: 100%;
    border: 2px solid #00001a;
  }
  
  #printButton{    
    margin-bottom: 5px;
  }
}

@media print{
  #printButton{
    display: none;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <button id="printButton">Print Page</button>

  <div >
  </div>
</body>

  •  Tags:  
  • Related