0

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?

3
  • Did you try style.display="none" ? Commented Nov 25, 2013 at 12:49
  • what about setTimeout(function (){...print....},3000) ? Commented Nov 25, 2013 at 12:50
  • will document.write('asp.net') on a window.onload function do? :) Commented Nov 25, 2013 at 12:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, works very fine! :) Thanks. I still have a question. On IE I have header (page name, pages,etc) and footer (URI) to printed pages. How can I get rid of them?
@dpv Only way I know of would to be edit the Print Setup - Go to the Settings, select print and then select Page Setup. There you can set the Header and Footer to be empty. This will only work on the machine you apply this to, so others will still receive the headers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.