MDB
MDB

Reputation: 360

CSS in print area

$("#btnPrint").on('click', function(){
    var toPrint = document.getElementById('printDiv');
    var popupWin = window.open('', '_blank', 'width=1250,height=850,location=no,left=200px,');
    popupWin.document.open();
    popupWin.document.write('<html><body onload="window.print()">')
    popupWin.document.write(toPrint.innerHTML);
    popupWin.document.write('</html>');
    popupWin.document.close()
});

This is my code for printing a specific part in the HTML. Upon clicking the button, a window will pop-out then the print page will show. I want to change the font-size of the labels inside the printDiv but I can't change it. I have also tried :

@media print {
    label { font-size: 10px; }
}

But It didn't work for me. How am I going to do that?

Upvotes: 2

Views: 1496

Answers (1)

Tom Dickson
Tom Dickson

Reputation: 622

So you are launching a new window which does not carry your defined CSS file with it. Instead, you can define a printable div and use the window.print() javascript method.

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

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}
label { font-size: 20px; }
@media print {
  label {
    font-size: 10px;
  }
}
<button type="button" onclick="printDiv('print-area')" class="btn btn-primary">Print Div</button>
<div id="print-area">
  <form class="form-group">
    <label for="test-label">Test</label>
    <input />
  </form>
</div>

Upvotes: 1

Related Questions