Fadly Dzil
Fadly Dzil

Reputation: 2226

Print style sheet not influence using javascript

I have declare a css to styling page and print in css like this :

@page{
size :A4 landscape;
}

@media print {
table{
    border-collapse: collapse;
    font-family : serif;
    font-size : 10px;
}

table, th, td{
    border : 1px solid black;
}

th{
    text-align: center;
}

th:first-child{
    width: 10%;
}

td{
    background-color: red;
    color: blue;
}
}

This is css is successfully loaded in browser, I have check it.

Now, I have a js function like this to manage print page :

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

}

You know,I have a table, actually, this is the table in a modal :

<table class="table table-bordered" id="table-struk">
<thead>
    <tr>
        <th style="width: 30%;">Item</th>
        <th style="width: 15%;">By</th>
        <th style="width: 18%;">Harga</th>
        <th style="width: 2%;">Qty</th>
        <th style="width: 30%;">Sub Total</th>
    </tr>

</thead>

<tbody>

    <tr><td>Gunting</td><td>Arif</td><td>85000</td><td>2</td><td>170000</td></tr></tbody>

<tfoot>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Jumlah Qty :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2">Kasir 1</td>
        <td colspan="2">Total Pembayaran :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Cust. Bayar :</td>
        <td></td>
    </tr>
    <tr>
        <td colspan="2"></td>
        <td colspan="2">Kembali :</td>
        <td></td>
    </tr>
</tfoot>
</table>

And this is the button to use this function :

<button class="btn btn-success" onclick='
               w = window.open();
               w.document.write($("#modalContent").html());
               w.print();w.close();' 
      type="button">Print Test</button>

My question is, the css is not working, The page now can be print, but cannot using style form css above, Any help, it so appreciated.

Upvotes: 2

Views: 100

Answers (1)

Weedoze
Weedoze

Reputation: 13953

You should inject the css inside your new window with the media="print"

Use the code hereunder and replace the href value with the path to your css file

var w= window.open();
w.document.write('<html><head><title></title>');
w.document.write( "<link rel=\"stylesheet\" href=\"style.css\" type=\"text/css\" media=\"print\"/>" ); //Inject CSS
w.document.write('</head><body >');
w.document.write($("#modalContent").html());//Your data
w.document.write('</body></html>');

mywindow.print();
mywindow.close();

Upvotes: 1

Related Questions