简体   繁体   中英

How to print css of a table

I need to get the table printed along with it's css using jQuery. I have included @media print section in my css file. But when i click the print button, in print preview it only displays basic html layout.

Following is the Html:

<div>
        <table id="myTable">
            <tr>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Age</th>
            </tr>
            <tr id="clo1">
                <td>bill</td>
                <td>gates</td>
                <td>51</td>
            </tr>
            <tr id="clo2">
                <td>larry</td>
                <td>page</td>
                <td>61</td>
            </tr>
            <tr id="clo3">
                <td>steve</td>
                <td>jobs</td>
                <td>71</td>
            </tr>
        </table>
    </div>
    <div class="printMe">
        <button id="print" type="submit">
            Print
        </button>
    </div>

Following is my Css:

@media print {

th, td {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: #000000;
}
tr {
    border: 1px solid gray;
}
td {
    width: 200px;
    padding: 3px;
}
th {
    background-color: #D2E0E8;
    color: #003366
}
table {
    border: 1pt solid gray;
    text-align: center;
}
}


@media screen {

th, td {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 18px;
    color: #000000;
}
tr {
    border: 1px solid gray;
}
td {
    width: 200px;
    padding: 3px;
}
th {
    background-color: #D2E0E8;
    color: #003366
}
table {
    border: 1pt solid gray;
    text-align: center;
}
}

Following is my script.js:

$(document).ready(function() {
$(".printMe #print").click(function() {
    var divToPrint = document.getElementById('myTable');
    var popupWin = window.open('', '_blank', 'width=auto,height=auto');
    popupWin.document.open();
    popupWin.document.write($('#myTable').html());
    popupWin.print();
    popupWin.document.close();
});
});

Create two separate CSS files. One for @media screen. Underneath that, create a new CSS file for @media print. Like this:

<link rel="stylesheet" href="css/screen.css" media="screen" />
<link rel="stylesheet" href="css/print.css" media="print" />

Screen CSS:

/* Normal screen CSS (no @media required) */

Print CSS:

@media print { }

Always works for me! Good luck!

You're opening a brand new window which doesn't have any reference to your stylesheet. Try this:

popupWin.document.open();
popupWin.document.write('<html><head><link rel="stylesheet" media="print" type="text/css" href="print.css"></head><body>');
popupWin.document.write($('#myTable').html());
popupWin.document.write('</body></html>');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM