Search code examples
javascripthideprint-preview

print content of a div except some element in it, doesnt work


I want to print content of a div, and don't want to show some element in this div in print preview, I tried to give noprint class to those element in @media print, but no success! please help! this is Javascript

<script type="text/javascript">
    function PrintPanel() {
        var panel = document.getElementById("content");
        var printWindow = window.open('', '', 'height=400,width=800');
        printWindow.document.write('<html><head><title>DIV Contents</title>');
        printWindow.document.write('</head><body >');
        printWindow.document.write(panel.innerHTML);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        setTimeout(function () {
            printWindow.print();
        }, 500);
        return false;
    }

</script>

this is css

<style>
    .noprint {
        color: red;
    }

    @media print {
        p {
            color: green;
        }

        .noprint {
            display: none;
        }
    }
</style>

and this is html

<body>
<div id="content">
    <p>show this, in print preview</p>

    <div class="noprint">
        dont show this, in print preview!
    </div>
</div>
<a id="btnPrint" runat="server" Text="Print" onclick="PrintPanel();" style="cursor:pointer;">print</a>

I provide a sample in jsfiddle: sample link


Solution

  • Actually the newly created window using window.open does not have any style attached to it.

    Here is a snapshot

    Snapshot of the newly created window

    Style can be added to it by adding inline style in the following code

    printWindow.document.write('<html><head><style media="print">' +
                'p {color: green;}.noprint {display: none !important;}</style><title>DIV Contents</title>');