Tuesday, 15 February 2011

Appling style for the Print Preview using Javascript

If you see the previous post output of the Print Preview window, you might be looking the style of the font and others contents are in default style. It means the style is not applied to the Preview window.

So to include the style for the print preview, we just have to include the style sheet html tag with the popup window. If you are not aware of what are the style sheets applied to the page, view the source of the page using View Source (IE), View page source (Chrome, Firefox) and find out the style sheet included line on the page (with link tag). Then you can place the same line to the popup window using Javascript.

Look at the following Javascript function.
<script language="javascript" type="text/javascript">
    function PrintContent() {
        printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1,resizable=1");
        var strContent = "<html><head>"; // If you use this script inside <head> on the page, there might be error. So I am keeping inside body (becaue of <head>)
        strContent = strContent + "<title>Print Preview</title>";
        strContent = strContent + "<link href=\"App_Themes/Default/Default.css\" type=\"text/css\" rel=\"stylesheet\" />";
        strContent = strContent + "</head><body>";
        strContent = strContent + "<div style='width:100%;text-align:right;'>";
        strContent = strContent + "<input type='button' id='btnPrint' value='Print' style='width:100px' onclick='window.print()' />";
        strContent = strContent + "<input type='button' id='btnCancel' value='Cancel' style='width:100px' onclick='window.close()' />";
        strContent = strContent + "</div>";
        strContent = strContent + "<div style='width:100%;'>";
        strContent = strContent + document.getElementById('news').innerHTML;
        strContent = strContent + "</div>";
        strContent = strContent + "</body>";
The same previous post preview output with style shown as:
Preview before Printing with the styles used on the normal page

download the source code here

0 Responses to “Appling style for the Print Preview using Javascript”

Post a Comment