ASP.NET - printing a page - Asked By rajeshwari balu on 31-Aug-11 06:31 AM

Hi friends

 how to print a page in default printer and printing receipt in receipt printer. please send me some logic

thanks
Cos mos replied to rajeshwari balu on 31-Aug-11 06:40 AM
hi,

protected void PrintFile_Click (object sender, System.EventArgs e)
{
printDialog1.Document = ThePrintDocument;
string strText = this.richTextBox1.Text;
myReader = new StringReader(strText);
if (printDialog1.ShowDialog() ==
DialogResult.OK)
{
this.ThePrintDocument.Print();
}
}
protected void
ThePrintDocument_PrintPage (object
sender,System.Drawing.Printing.PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPosition = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
string line = null;
Font printFont = this.richTextBox1.Font;
SolidBrush myBrush = new
SolidBrush(Color.Black);
// Work out the number of lines per page, using the
MarginBounds.
linesPerPage = ev.MarginBounds.Height / printFont.GetHeight(ev.Graphics);
// Iterate over the string using the StringReader,
printing each line.
while(count < linesPerPage &&
((line=myReader.ReadLine()) != null))
{
// calculate the next line position based on the
height of the font according to the printing device
yPosition = topMargin + (count * printFont.GetHeight(ev.Graphics));
// draw the next line in the rich edit control
ev.Graphics.DrawString(line, printFont, myBrush, leftMargin, yPosition, new StringFormat());
count++;
}
// If there are more lines, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
myBrush.Dispose();
}



Print
Preview

PrintPreview
behaves a heck of a lot like Print as seen below:

protected void PreviewFile_Click
(object sender, System.EventArgs e)
{
try
{
string strText = this.richTextBox1.Text;
// read string from editor window
myReader = new StringReader(strText);
PrintPreviewDialog printPreviewDialog1 = new
PrintPreviewDialog(); // instantiate new print
preview dialog
printPreviewDialog1.Document = this.ThePrintDocument
;
printPreviewDialog1.BorderStyle = FormBorderStyle.Fixed3D ;
printPreviewDialog1.ShowDialog(); // Show the print
preview dialog, uses print page event to draw preview screen
}
catch(Exception exp)
{
System.Console.WriteLine(exp.Message.ToString());
}
}

Reena Jain replied to rajeshwari balu on 31-Aug-11 06:41 AM
hi,

I would suggest you to use Report Viewer Control.You can do easily many things easily with report viewer control including printing and repeating headers on multiple pages without any effort.ReportViewer is a freely
redistributable control that enables embedding reports in applications developed using the .NET Framework. Reports are designed with drag-and-drop simplicity using Report Designer included in Visual Studio 2005 (Standard
editon and above.) There is a WinForms and a WebForms version of the control.
Find more info about report viewer control in below links:
http://www.gotreportviewer.com/

here is one more good link for you if you don't want to use report viewer
http://www.dotnetcurry.com/ShowArticle.aspx?ID=92

Hope this will help you
dipa ahuja replied to rajeshwari balu on 31-Aug-11 06:54 AM
Untitled document
<script type="text/javascript">
   function CallPrint(strid) {
     var prtContent = document.getElementById(strid);
     var WinPrint = window.open('', '', 'letf=0,top=0,width=400,height=400,toolbar=0,scrollbars=0,status=0');
     WinPrint.document.write(prtContent.innerHTML);
     WinPrint.document.close();
     WinPrint.focus();
     WinPrint.print();
     WinPrint.close();
 
   }
</script>
 
 
<div id="divPrint">
   <%--Put Controls that you want to print--%>
</div>
 
<input type="button" value="print " id="btnPrint" runat="Server"
onclick="javascript:CallPrint('divPrint')" />
 
rajeshwari balu replied to dipa ahuja on 31-Aug-11 07:10 AM
hi i want to set the printer name to print the documents.
if it is first printer
     i print document
if it is second printer
     i print receipt

so i want to mention the name
Anoop S replied to rajeshwari balu on 31-Aug-11 07:19 AM
use PrinterSettings.PrinterName Property ->Gets or sets the name of the printer to use.
The following code example specifies the target printer by setting the PrinterName property, and if the IsValid is true, prints the document on the specified printer. The example has three prerequisites:
A variable named filePath has been set to the path of the file to print.
A method named pd_PrintPage, which handles the PrintPage event, has been defined.
A variable named printer has been set to the printer's name.


public void Printing(string printer) {
  try {
    streamToPrint = new StreamReader (filePath);
    try {
      printFont = new Font("Arial", 10);
      PrintDocument pd = new PrintDocument(); 
      pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
      // Specify the printer to use.
      pd.PrinterSettings.PrinterName = printer;

      if (pd.PrinterSettings.IsValid) {
         pd.Print();
      } 
      else {	
         MessageBox.Show("Printer is invalid.");
      }
    } 
    finally {
      streamToPrint.Close();
    }
  } 
  catch(Exception ex) {
    MessageBox.Show(ex.Message);
  }
}

http://msdn.microsoft.com/en-us/library/system.drawing.printing.printersettings.printername.aspx


Radhika roy replied to rajeshwari balu on 31-Aug-11 07:26 AM
Try this code-

//Generating Pop-up Print Preview page
function getPrint(print_area)
{
    //Creating new page
    var pp = window.open();
    //Adding HTML opening tag with <HEAD> … </HEAD> portion 
    pp.document.writeln('<HTML><HEAD><title>Print Preview</title>')
    pp.document.writeln('<LINK href=Styles.css type="text/css" rel="stylesheet">')
    pp.document.writeln('<LINK href=PrintStyle.css ' + 
                        'type="text/css" rel="stylesheet" media="print">')
    pp.document.writeln('<base target="_self"></HEAD>')

    //Adding Body Tag
    pp.document.writeln('<body MS_POSITIONING="GridLayout" bottomMargin="0"');
    pp.document.writeln(' leftMargin="0" topMargin="0" rightMargin="0">');
    //Adding form Tag
    pp.document.writeln('<form method="post">');

    //Creating two buttons Print and Close within a HTML table
    pp.document.writeln('<TABLE width=100%><TR><TD></TD></TR><TR><TD align=right>');
    pp.document.writeln('<INPUT ID="PRINT" type="button" value="Print" ');
    pp.document.writeln('onclick="javascript:location.reload(true);window.print();">');
    pp.document.writeln('<INPUT ID="CLOSE" type="button" ' + 
                        'value="Close" onclick="window.close();">');
    pp.document.writeln('</TD></TR><TR><TD></TD></TR></TABLE>');

    //Writing print area of the calling page
    pp.document.writeln(document.getElementById(print_area).innerHTML);
    //Ending Tag of </form>, </body> and </HTML>
    pp.document.writeln('</form></body></HTML>'); 
}

Hope this will help you.
rajeshwari balu replied to Anoop S on 31-Aug-11 07:27 AM
here the documents are in xml format. so it s possible to print
Radhika roy replied to rajeshwari balu on 31-Aug-11 07:27 AM
Follow these steps-

Step 1: Create a PrintHelper class. This class contains a method called PrintWebControl that can print any control like a GridView, DataGrid, Panel, TextBox etc. The class makes a call to window.print() that simulates the print button.
Note: I have not written this class and neither do I know the original author. I will be happy to add a reference in case someone knows. 
C# 
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
 
public class PrintHelper
{
  public PrintHelper()
    {
    }
 
  public static void PrintWebControl(Control ctrl)
    {
      PrintWebControl(ctrl, string.Empty);
    }
 
  public static void PrintWebControl(Control ctrl, string Script)
    {
    StringWriter stringWrite = new StringWriter();
      System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
    if (ctrl is WebControl)
      {
      Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
      }
    Page pg = new Page();
      pg.EnableEventValidation = false;
    if (Script != string.Empty)
      {
        pg.ClientScript.RegisterStartupScript(pg.GetType(),"PrintJavaScript", Script);
      }
    HtmlForm frm = new HtmlForm();
      pg.Controls.Add(frm);
      frm.Attributes.Add("runat""server");
      frm.Controls.Add(ctrl);
      pg.DesignerInitialize();
      pg.RenderControl(htmlWrite);
    string strHTML = stringWrite.ToString();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.Write(strHTML);
    HttpContext.Current.Response.Write("<script>window.print();</script>");
    HttpContext.Current.Response.End();
    }
}
 
Step 2: Create two pages, Default.aspx and Print.aspx. Default.aspx will contain the controls to be printed. Print.aspx will act as a popup page to invoke the print functionality.
Step 3: In your Default.aspx, drag and drop a few controls that you would like to print. To print a group of controls, place them all in a container control like a panel. This way if we print the panel using our PrintHelper class, all the controls inside the panel gets printed.
Step 4: Add a print button to the Default.aspx and in the code behind, type the following code:
C#
protected void btnPrint_Click(object sender, EventArgs e)
    {
      Session["ctrl"] = Panel1;
      ClientScript.RegisterStartupScript(this.GetType(), "onclick""<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
    }

Step 5: In the Page_Load event of Print.aspx.cs, add the following code:
C#
 
protected void Page_Load(object sender, EventArgs e)
    {
    Control ctrl = (Control)Session["ctrl"];
    PrintHelper.PrintWebControl(ctrl);
    }

Hope this will help you/.
Anoop S replied to rajeshwari balu on 02-Sep-11 12:25 AM
A simple way to print an XM data onto the Console window is by using an object of XmlDocument.

here is a sample code snippet:

XmlDocument doc = new XmlDocument();
doc.LoadXML(("<clientinfo><servicetype>korea</servicetype><servertype>sakray</servertype></clientinfo>"));
doc.Save(Console.Out);