Printing aspx page wtithout viewing the content


Often we need to print an aspx page without viewing the page. Suppose we are on an aspx page which has a print button. Now clicking on print button should print particular portion of the page instead of printing the full page.

Printing is a common event for web applications. Now sometimes the requirement could be different.

Scenario 1: Page View.aspx has a 'Print' button. Clicking the button should print the content of a different page.

Scenario 2: Clicking the 'Print' button should not print the whole View.aspx, instead it should print a particular portion from the page.

Scenario 3: View.aspx page should not view the printable portion. Means user should view a particular portion on the page and while printing it prints some other portions which was not viewed on the page.

Now when we try to fulfill the requirement of 'Scenario 1' then this could be easily done by redirecting the page to the printable page(Printable.aspx) and writing the following code in Page_Load event.


protected void Page_Load(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "window.print()", true);
}


But for other Scenarios this is not applicable. Here lets code in a different way which is much more applicable on most of the Scenarios.

First create an aspx page called View.aspx

Write the following css


@media print {
.PrintOnly
{
font-size: 10pt;
line-height: 120%;

}

.NoPrint
{
display: none;
}
}
@media screen {
.PrintOnly
{
display: none
}
}


Now the media tag is a special tag. @media print works for the printable content and @media screen works for the viewable content.

Now use a div tag and use the css class 'PrintOnly'. include the content that has to be printed inside this div and the content which will only be viewed and not to be printed has to be inside other div that uses the css 'NoPrint'.


The print button should have the following event on click event


ClientScript.RegisterClientScriptBlock(this.GetType(), "key", "window.print()", true);


Now when users browse the View.aspx page then it will show just the content using 'NoPrint' CSS, where on the printed page will contain the content that was inside the div using 'PrintOnly' CSS.

The above code will help to implement the 'Print' feature on applications in a better and efficient way.

Hope it will be helpful.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: