dpv
dpv

Reputation: 157

Print asp.net with javascript

I want to print a aspx page but before printing I want to hide some controls from the page and after that I want to show again those controls. I'm using this code:

        String scriptText = "<script language='javascript'>";
        scriptText += "document.getElementById('textB1').style.visibility = \"hidden\";";
        scriptText += "document.getElementById('panel').style.visibility = \"hidden\";";           
        scriptText += "window.print();";
        scriptText += "document.getElementById('textB1').style.visibility = \"visible\";";
        scriptText += "document.getElementById('panel').style.visibility = \"visible\";";  
        scriptText += "</script>";
        ClientScript.RegisterStartupScript(this.GetType(), "Print", scriptText);

The problem is that I don't know how windows.print() works because the controls are still visible on my printed page. How to get the right time when the printed page was captured? Only after that, the controls to be set to visible?

Upvotes: 0

Views: 884

Answers (1)

Nunners
Nunners

Reputation: 3047

If you simply want to hide elements on a page whilst printing it is a much easier option to use the CSS print media type.

For more information on CSS Media Types see here

Example :

Add the following CSS to either your page or to a Stylesheet

@media print {
    .hiddenOnPrint {
        display:none;
    }
}

And then add this class to each of the controls you want to hide on your page whilst printing :

<asp:TextBox ID="textB1" runat="server" CssClass="hiddenOnPrint"></TextBox>
<asp:Panel ID="panel" runat="server" CssClass="hiddenOnPrint"></panel>

This is a much more controlled way to handle this as opposed to Javascript.

Example JSFiddle

Upvotes: 1

Related Questions