Sunday, 20 February 2011

Printing different parts of page using Javascript when Master Page, User Controls used



This example is used to understand on how to print different parts of pages using Javascript where some information comes from content form, some from User Control and some from Master Page. So our requirement is to consolidate all those parts together in meaningful way and show a popup to print.

Before going to any implementation, let us understand more on how the layout of the page will look like and what are the parts required to be printed. The following is the layout of the screen. Here

  • The Header and Footer are placed on Master Page as normal way.
  • The right side of the page shows advertisement, related links, three buttons which all are defined in a User Control
  • The page center part contains an advertisement and news which are from Content Page.
  • Addition to this the master page also includes another User Control to show the article stat which includes No of person Visited, Commented and Shared.

Here is the layout of the screen

Page layout from from which the different parts required to be printed

The requirements are

  1. In 1st example, let us print only the News from the content page (by removing the Advertisement).
  2. Print with Stat information on the Top and Related Topics on the bottom (Here Stat information is from one User Page, Related Topics from another User Control)
  3. Addition to Point 2, implement some additional information especially for the print which is not shown in the web page. (When we print a custom information, we are planning to place some value which shown in the header – Date)

The implementation goes as below

MasterWithUControls.Master (Master Page)

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterWithUControls.master.cs" Inherits="Printing.MasterWithUControls" %>
<%@ Register Src="~/RelatedLinks.ascx" TagName="ucLinks" TagPrefix="uc" %>
<%@ Register Src="~/ArticleStat.ascx" TagName="ucStat" TagPrefix="uc" %>
<!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>Print with Master Page Sample</title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
    <div id="header">
        <div style="height:60px;">
            <div style="float:left;background-color:#2E9AFE;width:25%;height:100%;">
                <h1 style="margin:0px;">TrueWins Media</h1>
                <strong><label id="lblCurrentDate" runat="server"></label> </strong>
            </div>
            <div style="float:left;background-color:#FF8000;width:75%;height:100%;">
                Advertisement
            </div>
        </div>
        <div style="height:20px;background-color:#AC5A5A;">
            <ul class="newsMenu" style="height:10px;">
                <li><a href="http://www.truewins.com/default.aspx">Home</a></li>
                <li><a href="http://www.truewins.com/news.aspx">News</a></li>
                <li><a href="http://www.truewins.com/views.aspx">Views</a></li>
                <li><a href="http://www.truewins.com/business.aspx">Business</a></li>
                <li><a href="http://www.truewins.com/cricket.aspx">Cricket</a></li>
                <li><a href="http://www.truewins.com/lifestyle.aspx">Lifestyle</a></li>       
                <li><a href="http://www.truewins.com/photos.aspx">Photos</a></li>
                <li><a href="http://www.truewins.com/audio.aspx">Video</a></li>
                <li><a href="http://www.truewins.com/events.aspx">Events</a></li>
                <li><a href="http://www.truewins.com/entertainment.aspx">entertainment</a></li>
                <li><a href="http://www.truewins.com/weather.aspx">Weather</a></li>
                <li><a href="http://www.truewins.com/epaper.aspx">ePaper</a></li>
                <li><a href="http://www.truewins.com/classifieds.aspx">Classifieds</a></li>
            </ul>
        </div>
        <div><marquee class="spotlight" scrollamount="1">Sensex opens up by 75 points on firm global cues || Goldman Sachs warns against investing in India, China || Investors cheer Axis Bank Q3 nos; scrip jumps 5.62 pc || Sensex gains for 2nd day; rises by 210 pts || Oil supplies from Iran not hurt by payments issue: Essar || SEBI effect: ADAG stocks rattled || Sensex snaps 2-day falling streak on selective buying; up 22 pts</marquee></div>
    </div>
    <div id="content">
        <div id='divRelatedLinks'>
            <uc:ucLinks ID="RelatedLinks" runat="server" />
        </div>
        <div id='divArticleStat'>
            <uc:ucStat id="ArticleStat" runat="server" />
        </div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            
        </asp:ContentPlaceHolder>
    </div>
    <div id="footer">
        <div>
            <ul>
                <li><a href="http://www.truewins.com/default.aspx">Home</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/news.aspx">News</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/views.aspx">Views</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/business.aspx">Business</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/cricket.aspx">Cricket</a></li>
                <li>|</li> 
                <li><a href="http://www.truewins.com/lifestyle.aspx">Lifestyle</a></li>       
                <li>|</li>    
                <li><a href="http://www.truewins.com/photos.aspx">Photos</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/audio.aspx">Video</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/events.aspx">Events</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/entertainment.aspx">entertainment</a></li>
                <li>|</li>        
                <li><a href="http://www.truewins.com/weather.aspx">Weather</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/epaper.aspx">ePaper</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/classifieds.aspx">Classifieds</a></li>
            </ul>
        </div>
        <div>
            <ul style="margin:0px;">
                <li><a href="http://www.truewins.com/AbountUs.aspx" target="_blank">About us</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/ContactUs.aspx" target="_blank">Contact us</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/Careers.aspx" target="_blank">Careers</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/privacypolicy.aspx" target="_blank">Policy</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/Disclaimer.aspx" target="_blank">Disclaimer</a></li>
                <li>|</li>
                <li><a href="http://www.truewins.com/sitemap/sitemap.aspx" target="_blank">Sitemap</a></li>
            </ul>
            <div>Copyright © 2011 TrueWins Media Limited. All Rights Reserved.</div>
        </div>
    </div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
        lblCurrentDate.InnerText = System.DateTime.Today.ToLongDateString();
}
ArticleStat.ascx (User Control)
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ArticleStat.ascx.cs" Inherits="Printing.ArticleStat" %>
<div id="ArticleStat">
    Viewed : <b><asp:Label ID="lblNoofPersonViewed" runat="server" ></asp:Label></b>
    <span style="padding-left:20px">Comments : <b></span><asp:Label ID="lblNoofComments" runat="server" ></asp:Label></b>
    <span style="padding-left:20px">Shared : <b></span><asp:Label ID="lblNoofShared" runat="server" ></asp:Label></b>
</div>
protected void Page_Load(object sender, EventArgs e)
{
    lblNoofComments.Text = "23";
    lblNoofPersonViewed.Text = "1445";
    lblNoofShared.Text = "56";
}

RelatedLinks.ascx (User Control)
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="RelatedLinks.ascx.cs" Inherits="Printing.RelatedLinks" %>
<div style="float:right;">
    <ul class="buttonMenu">
        <li><a href="#" onclick="PrintContent()">Print</a></li>
        <li><a href="http://www.truewins.com/default.aspx">Email</a></li>
        <li><a href="http://www.truewins.com/default.aspx">Comment</a></li>
        <li><a href="http://www.truewins.com/default.aspx">Share</a></li>
    </ul>
    <div style="height:250px;width:250px;background-color:#6BD451;text-align:center;border:solid 1px black;">
        <p style="padding-top:100px;font-size:medium;">Advertisement</p>
    </div>
    <div id="RelatedTopics">
        <span style="font-size:13px;font-weight:bold">Related Topics</span>
        <ul style="text-align:left;margin-left:20px;margin-top:5px;">
            <li><a href="#">Petrol price should have been hiked by Rs 3.72, says IOC</a></li>
            <li><a href="#">Oil price over $100 'not unrealistic', says Iran</a></li>
            <li><a href="#">Oil price over $100 'not unrealistic', says Iran</a></li>
            <li><a href="#">ADAG-SEBI settlement charge at record Rs 50 cr</a></li>
        </ul>
    </div>
</div>

PageUControlPrint.ascx (Web Content Page)
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterWithUControls.Master" AutoEventWireup="true" CodeBehind="PageUControlPrint.aspx.cs" Inherits="Printing.PageUControlPrint" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div id="news">
        <h3 id="Title">Sensex rises in noon trade</h3>
        <div id="newsRelatedAd" style="width:700px;height:100px;background-color:#FE2EF7">Advertisement</div>
        <p>A benchmark index of Indian equities markets Tuesday rose in noon trade, helped by strong earnings reported by corporates. Gainers in front-line stocks were led by IT and telecom firms. The 30-scrip sensitive index (Sensex) of the Bombay Stock Exchange (BSE), which opened at 18,983.2 points, was ruling at 19,008.28 points -- up 126.03 points or 0.67 % from its previous close at 18,882.25 points.</p>
        <p>The 50-scrip S&P CNX Nifty of the National Stock Exchange too was in the green, trading 36.55 points or 0.65 % higher at 5,691.3 points.</p>
        <p>Broader markets were, however, trading dull, with the BSE midcap index ruling 0.24 % up and the BSE smallcap index trading 0.34 % higher.</p>
        <p>Realty, power and energy stocks saw some selling, while gains were seen in IT and telecom scrips.</p>
        <p>The market breadth was positive, with 1,431 stocks advancing compared to 1,133 scrips on the decline, while 107 stocks remained unchanged.</p>
        <p>Among gainers on the Sensex were TCS, Wipro, Cipla and Tata Motors, while the losers included Tata Power, Reliance Infra, Jindal Steel and DLF.</p>
        <p>Most other Asian stock markets were ruling higher Tuesday, except the Chinese stocks markets which continued to loose after the Chinese central bank's latest move to tighten monetary policy cast a gloom on trading.</p>
        <p>The Chinese Shanghai Composite index shed 0.44 % to trade at 2,694.68 points, while Hong Kong's Hang Seng was ruling 0.75 % higher at 24,339.27 points.</p>
        <p>The Japanese Nikkei closed flat at 10,518.98 points.</p>
    </div>
</asp:Content>

The following are Javascript implementation for each we discussed before. (Please add this Javascript code in Master Page. Also refer Note section at the end of the implementation)

  1. In 1st example, let us print only the News from the content page (by removing the Advertisement).
    <script language="javascript" type="text/javascript">
       function PrintContent() {
           printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1,resizable=1");
    
           var strContent = "<html><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>";
    
           // Writing News Contents
           strContent = strContent + "<div style='width:100%;'>";
    
           var divNews = document.createElement('div');
           divNews.innerHTML = document.getElementById('news').innerHTML;
           for (var i = 0; i < divNews.childNodes.length; i++) {
               if (divNews.childNodes[i].id == 'newsRelatedAd')
                   divNews.childNodes[i].className = "Invisible"; // newsDiv.removeChild(newsDiv.childNodes[i]);
           }
    
           strContent = strContent + divNews.innerHTML;
           strContent = strContent + "</div>";
    
           strContent = strContent + "</body>";
           printWindow.document.write(strContent);
           printWindow.document.close();
           printWindow.focus();
       }
    </script>
  2. Print with with Stat information on the Top and Related Topics on the bottom (Here Stat information is from one User Page, Related Topics from another User Control)
    <script language="javascript" type="text/javascript">
       function PrintContent() {
           printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1,resizable=1");
    
           var strContent = "<html><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>";
    
           // Writing Stat Contents
           strContent = strContent + "<div style='width:100%;'>";
           var divPrintArticleStat = document.createElement('div');
           divPrintArticleStat.innerHTML = document.getElementById('divArticleStat').innerHTML;
           for (var i = 0; i < divPrintArticleStat.childNodes.length; i++) {
               if (divPrintArticleStat.childNodes[i].id == 'ArticleStat')
                   divPrintArticleStat.childNodes[i].id = "";
           }
           strContent = strContent + divPrintArticleStat.innerHTML;
           strContent = strContent + "</div>";
           strContent = strContent + "<br / >"
    
           // Writing News Contents
           strContent = strContent + "<div style='width:100%;'>";
    
           var divNews = document.createElement('div');
           divNews.innerHTML = document.getElementById('news').innerHTML;
           for (var i = 0; i < divNews.childNodes.length; i++) {
               if (divNews.childNodes[i].id == 'newsRelatedAd')
                   divNews.childNodes[i].className = "Invisible"; // newsDiv.removeChild(newsDiv.childNodes[i]);
           }
    
           strContent = strContent + divNews.innerHTML;
           strContent = strContent + "</div>";
    
           //Writing Related Topics Contents
           strContent = strContent + "<br / >"
           strContent = strContent + "<div style='width:100%;'>";
           strContent = strContent + document.getElementById('RelatedTopics').innerHTML;
           strContent = strContent + "</div>";
    
           strContent = strContent + "</body>";
           printWindow.document.write(strContent);
           printWindow.document.close();
           printWindow.focus();
       }
    </script>
  3. Addition to Point 2, implement some additional information especially for the print which is not shown in the web page. (When we print a custom information, we are planning to place some value which shown in the header – Date)
    <script language="javascript" type="text/javascript">
       function PrintContent() {
           printWindow = window.open("", "mywindow", "location=0,status=0,scrollbars=1,resizable=1");
    
           var strContent = "<html><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>";
    
           // Writing Stat Contents
           strContent = strContent + "<div style='width:100%;'>";
           var divPrintArticleStat = document.createElement('div');
           divPrintArticleStat.innerHTML = document.getElementById('divArticleStat').innerHTML;
           for (var i = 0; i < divPrintArticleStat.childNodes.length; i++) {
               if (divPrintArticleStat.childNodes[i].id == 'ArticleStat')
                   divPrintArticleStat.childNodes[i].id = "";
           }
           strContent = strContent + divPrintArticleStat.innerHTML;
           strContent = strContent + "</div>";
           strContent = strContent + "<br / >"
    
           // Writing News Contents
           strContent = strContent + "<div style='width:100%;'>";
    
           var divNews = document.createElement('div');
           divNews.innerHTML = document.getElementById('news').innerHTML;
           for (var i = 0; i < divNews.childNodes.length; i++) {
               if (divNews.childNodes[i].id == 'newsRelatedAd')
                   divNews.childNodes[i].className = "Invisible"; // newsDiv.removeChild(newsDiv.childNodes[i]);
           }
    
           strContent = strContent + divNews.innerHTML;
           strContent = strContent + "</div>";
    
           //Writing Related Topics Contents
           strContent = strContent + "<br / >"
           strContent = strContent + "<div style='width:100%;'>";
           strContent = strContent + document.getElementById('RelatedTopics').innerHTML;
           strContent = strContent + "</div>";
    
           // Adding Information about Printed Date and Footer Info 
           strContent = strContent + "<br / >"
           strContent = strContent + "<div style='width:100%;text-align:center'>";
           strContent = strContent + "Printed from <b>http://www.truewins.com (TrueWins Media)</b> on " + document.getElementById("<%= lblCurrentDate.ClientID %>").innerHTML + ".";
           strContent = strContent + "<br / >"
           strContent = strContent + "All Rights Reserved.";
           strContent = strContent + "</div>";
    
           strContent = strContent + "</body>";
           printWindow.document.write(strContent);
           printWindow.document.close();
           printWindow.focus();
       }
    </script>
Note: I told you to add the Javascript code in the Master Page. Why?

You can even add in any page, either in User Controls, Content Page (or refer the Javascript as external file). But only you need to keep in mind that, if the Javascript refers any server controls (Text Box, Hyperlink etc,), then the Javascript must be placed on that page only.

In our Example, the third point (some additional information) prints the current date in the footer. The javascript refers the value from a server control (runat='server') using document.getElementById("<%= lblCurrentDate.ClientID %>").innerHTML (check the 3rd implementation line #48 - highlight) in Master Page. The value for that server control is set by the C# code. When printing, the Javascript gets the value and print. So We required to place the Javascript in Master Page.

If we have lots of server control which are required to be referred in Javascript, then simply declare a <div> with some id (and declare the server control inside it) and get that <div> in Javascript instead of getting server control. It means if we always refer a client side controls (only html controls) in Javascript, the Javascript can be placed in any User Controls, Web content Page or Master Page. Once the runtime render the page and show in the browser (client side) all controls are same and Javascript is in a single page only.

The output of the web page, print preview of point 3 would be as follows

Web Page screen layout for printing different parts

Print Preview output of Implementation of Point 3 

If you would like the print dialog box once the preview window open (for selecting the printer, paper size to print), you can add the add following highlight (printWindow.print();) code in the Javascript
// Normal code as defined above
       strContent = strContent + "</body>";
       printWindow.document.write(strContent);
       printWindow.document.close();
       printWindow.print();
       printWindow.focus();
Note: In all the source code, where ever <br / > is used, there is no space between / and >. As blogger has some issue, I use space.

download the source code here


2 Responses to “Printing different parts of page using Javascript when Master Page, User Controls used”

  • Anonymous says:
    13 October 2011 at 21:47

    Page style is not working in Usercontrol

  • Thiru says:
    13 October 2011 at 23:21

    Anonymous,
    You required to refer the style sheet referred in user control in the print preview also.

    For Ex you required to add like line #7 which used in the javascript,
    strContent = strContent + "<link href=\"App_Themes/Default/Default.css\" type=\"text/css\" rel=\"stylesheet\" />";

    If you still face issue, let me know.

Post a Comment