Printing ASPX Page by Hiding Some of the Page Elements Dynamically in ASP.Net
If we build a content management system, users should be given an option to print the content. It will be tedious and time consuming, if we build a separate page for printing the page which hides some of the unwanted element on the page for printing. For example, we will have advertisements or links to other tutorials on the same page which is not required to be printed.
This little article will help us to make the aspx page a printer friendly page that hides some of the unwanted elements on the page using CSS style sheet.
To do this, we can include all the printable content inside a DIV tag and other non printable elements like ads inside another DIV tag. We can include a style sheet to the aspx page through <link> tag with attribute media="print" which will be applied to the page dynamically when the user orders for a print. We can define styles in the print style sheet that hide some of the unwanted elements from the page. So, when the user clicks print page, the styles in the stylesheet with attribute media="print" will be applied and will hide the unwanted page elements.
Refer the below code.
ASPX Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="PrintPage.aspx.cs" Inherits="PrintPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<link href="PrintStyle.css" rel="stylesheet" type="text/css" media="print"/>
</head>
<body>
<form id="form1" runat="server">
<div id="Content" class="Printable">
Test
</div>
<div id="Advertisement" class="NonPrintable">
Ads
</div>
</form>
</body>
</html>
PrintStyle.css
.NonPrintable
{
display: none;
}
.Printable
{
width:100%;
}
Thus, with this approach we can prevent a building a separate page for print preview. The above styles will hide the advertisement div and will make the content div to stretch to the full page. Thus, the printed page will not have the advertisements on the page printed.
|