Monday, 14 February 2011

How to show preview before printing a Web Page



We will take the same example explained in previous post and expand it. When a user clicks the Print button the system required to show a preview popup window. That popup window should also contains two buttons (Print – to show Print dialog, Cancel – to close the popup).

Another point to note here is, normally when we print we required to print some part of the page. Normally we don’t print header, footer, left menu, right sections (which are common across the pages). We required to print only the important information which are mostly between the sections mentioned.

To achieve this, we required to declare a div control with some Id. This control should be the container for the information which is required to print. When we write the printing information to the popup window, we can only write the innerHTML of the div container declared (In our example, we are print only the news and not header, footer, menu etc.,).

Include a Javascript on the page
<script language="javascript" type="text/javascript">
    function PrintContent()
    {
        printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1");
        printWindow.document.write("<div style='width:100%;text-align:left;'>");
        printWindow.document.write("<input type='button' id='btnPrint' value='Print' style='width:100px' onclick='window.print()' />");
        printWindow.document.write("<input type='button' id='btnCancel' value='Cancel' style='width:100px' onclick='window.close()' />");
        printWindow.document.write(document.getElementById('news').innerHTML);
        printWindow.document.write("</div>");
        printWindow.document.close();
        printWindow.focus();
    }
</script>
and modify the print button (43th line - previous post example) to call the Javascript function
<li><a href="#" onclick="PrintContent()">Print</a></li>
The output of clikcing the print button will be as following figure
Print with Preview

download the source code here



0 Responses to “How to show preview before printing a Web Page”

Post a Comment