C# .NET - simple way to print

Asked By kshama parashar
11-Oct-11 02:45 AM
Helo to EggHeadCafe Team I have an windows application in c#.
In panel i have some textboxes and its values
on button click i want print the values inside the panel
and also i wants to see print preview as i don;t have a printer so i will check it by print preview

Plz tell me step by step as searched a lot but didn't find in easy way plz tell in easy way
  Suchit shah replied to kshama parashar
11-Oct-11 02:47 AM

If you want to show a print preview page before printing any page, then you have to make a page like the one that currently is showing.

Or, if you want to print a particular section of that page, like only a DataGrid, HTML table, or any other section, and you also need to preview that in a separate page before printing, you have to create a separate print preview page to show, which is more difficult for you.

I have introduced a technique to avoid this problem. You do not need to create a separate page for print preview. You just use the JavaScript code in Script.js to create a print preview page dynamically. It will take less time to implement and so is faster. Hopefully, it will be helpful for you.

Background

I was developing a report module in my existing project. The report contents are generated dynamically by giving input (like generate by status, date range, etc). And, there is a print button to print. My client wanted to view a print preview page before printing, but we had already completed this module then. It was a really hard situation for my developers to build a print preview page for all the reports. I got this idea during that situation.

Using the code

You will just add the Script.js file in your project. The following code has been written in that file.

Source 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>'); 
}

The getPrint(print_area) function takes the DIV ID of the section you want to print. Then, it creates a new page object and writes the necessary HTML tags, and then adds Print and Close buttons, and finally, it writes the print_area content and the closing tag.

Call the following from your ASPX page. Here, getPrint('print_area') has been added for printing the print_area DIV section. print_area is the DIV ID of the DataGrid and the other two will work for others DIVs. Whatever areas you want to print must be defined inside of DIV tags. Also include the Script.js file in the ASPX page.

'calling getPrint() function in the button onclick event
btnPrint.Attributes.Add("Onclick", "getPrint('print_area');")
btnTablePP.Attributes.Add("Onclick", "getPrint('Print_Table');")
btnPagepp.Attributes.Add("Onclick", "getPrint('Print_All');")

Download the source code to get the getPrint() function.

I have used the following code in the demo project to generate a sample DataGrid:

Private Sub PopulateDataGrid()
    'creating a sample datatable
    Dim dt As New System.Data.DataTable("table1")
    dt.Columns.Add("UserID")
    dt.Columns.Add("UserName")
    dt.Columns.Add("Phone")
    Dim dr As Data.DataRow
    dr = dt.NewRow
    dr("UserID") = "1"
    dr("UserName") = "Ferdous"
    dr("Phone") = "+880 2 8125690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "2"
    dr("UserName") = "Dorin"
    dr("Phone") = "+880 2 9115690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "3"
    dr("UserName") = "Sazzad"
    dr("Phone") = "+880 2 8115690"
    dt.Rows.Add(dr)
    dr = dt.NewRow
    dr("UserID") = "4"
    dr("UserName") = "Faruk"
    dr("Phone") = "+880 2 8015690"
    dt.Rows.Add(dr)
    DataGrid1.DataSource = dt
    DataGrid1.DataBind()
End Sub

Use the following code in a separate style sheet page. See PrintStyle.css if you want to hide the Print and Close buttons during printing.

#PRINT ,#CLOSE
{
    visibility:hidden;
}

Points of interest

I was facing a problem during print. Print was not working the first time I clicked it. I solved that problem by reloading by using location.reload(true); on that page.




http://www.codeproject.com/KB/aspnet/PrintPreview.aspx
  Reena Jain replied to kshama parashar
11-Oct-11 02:48 AM
Hi,

You can not show value in panel or group box. both are container where you can keep other controls. If you want to show data on a page then I will suggest you to use crystal report where you can even show print preview of data. But container only used to keep control, not to show data.

Hope this will help you
  kshama parashar replied to Reena Jain
11-Oct-11 02:51 AM
Helo Reena can u plz tell how to use Crystal Report to print as i am new
  kshama parashar replied to Suchit shah
11-Oct-11 02:52 AM
Helo Suchit I already told that i am making application in c# in windows application
  Anoop S replied to kshama parashar
11-Oct-11 03:03 AM
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>");
    }

The code stores the control in a Session variable to be accessed in the pop up page, Print.aspx. If you want to print directly on button click, call the Print functionality in the following manner :
 
PrintHelper.PrintWebControl(Panel1);
 
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);
    }
  Reena Jain replied to kshama parashar
11-Oct-11 03:05 AM
Hi,

sure. Crystal Report is a part of Add New Item templates available in Visual Studio. To add a report to the project, add a new item by Right Clicking on the project in Solution Explorer and selecting Add->Add New Item->Crystal Report.

The next step is to select the report document type from Crystal Report Gallery. Crystal Report Gallery provides three options Using the Report Expert, As a Blank Report, or From an Existing Report. So keep all options as default

By clicking the OK button adds Customers.rpt file to the project and launches Standard Report Expert wizard. where you can select a data source

for more detail check these links
http://www.c-sharpcorner.com/uploadfile/mahesh/crystalreportsintroduction11082005014959am/crystalreportsintroduction.aspx
http://www.codeproject.com/KB/cs/CreatingCrystalReports.aspx
  smr replied to kshama parashar
11-Oct-11 03:07 AM
hi

try this

This is a .NET approach to Simplified Printing in which, we are going to use a RichTextBox to cache all of our text for printing in printDocument.

Sample screenshot




private void Form1_Load(object sender, System.EventArgs e)
{
   // Write to richTextBox
 
   richTextBox1.Text = "                 " +
   DateTime.Now.Month + "/" + DateTime.Now.Day + "/" +
   DateTime.Now.Year + "\r\n\r\n";
   richTextBox1.AppendText("This is a greatly simplified Print " +
   "Document Method\r\n\r\n");
   richTextBox1.AppendText("We can write text to a richTextBox, " +
   "or use Append Text, " + "\r\n" + "or Concatenate a String, and " +
   "write that textBox. The " + "\r\n" + "richTextBox does not " +
   "even have to be visible. " + "\r\n\r\n" + "Because we use a " +
   "richTextBox it's physical dimensions are " + "\r\n" +
   "irrelevant. We can place it anywhere on our form, and set the " +
   "\r\n" + "Visible Property to false.\r\n\r\n");
   richTextBox1.AppendText("This is the document we will print. The " +
   "rich TextBox serves " + "\r\n" + "as a Cache for our Report, " +
   "or any other text we wish to print.\r\n\r\n");
   richTextBox1.AppendText("I have also included Print Setup " +
   "and Print Preview. ");
}
// Print Event
 
private void miPrint_Click(object sender, System.EventArgs e)
{
  if (printDialog1.ShowDialog() == DialogResult.OK)
  {
     printDocument1.Print();
  }
}
     
// OnBeginPrint
 
private void OnBeginPrint(object sender,
          System.Drawing.Printing.PrintEventArgs e)
{
  char[] param = {'\n'};
 
  if (printDialog1.PrinterSettings.PrintRange == PrintRange.Selection)
  {
     lines = richTextBox1.SelectedText.Split(param);
  }
  else
  {
     lines = richTextBox1.Text.Split(param);
  }
       
  int i = 0;
  char[] trimParam = {'\r'};
  foreach (string s in lines)
  {
     lines[i++] = s.TrimEnd(trimParam);
  }
}
// OnPrintPage
 
private void OnPrintPage(object sender,
               System.Drawing.Printing.PrintPageEventArgs e)
{
  int x = e.MarginBounds.Left;
  int y = e.MarginBounds.Top;
  Brush brush = new SolidBrush(richTextBox1.ForeColor);
       
  while (linesPrinted < lines.Length)
  {
  e.Graphics.DrawString (lines[linesPrinted++],
     richTextBox1.Font, brush, x, y);
  y += 15;
  if (y >= e.MarginBounds.Bottom)
  {
     e.HasMorePages = true;
     return;
  }
  else
  }
     e.HasMorePages = false;
  }
  }
}
// Page Setup
 
private void miSetup_Click(object sender, System.EventArgs e)
{
   // Call Dialog Box
 
   pageSetupDialog1.ShowDialog();
}
// Print Preview
 
private void miPreview_Click(object sender, System.EventArgs e)
{
   // Call Dialog Box
 
   printPreviewDialog1.ShowDialog();
   
}

refer
http://www.codeproject.com/KB/printing/simpleprintingcs.aspx
http://www.c-sharpcorner.com/UploadFile/mgold/PritinginCSharp11222005040630AM/PritinginCSharp.aspx
  Vickey F replied to kshama parashar
11-Oct-11 03:11 AM
You can try like this.

PrintDialog myPrintDialog = new PrintDialog();
System.Drawing.Bitmap memoryImage = new System.Drawing.Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(memoryImage, panel1.ClientRectangle);
if (myPrintDialog.ShowDialog() == DialogResult.OK)
{
System.Drawing.Printing.PrinterSettings values;
values = myPrintDialog.PrinterSettings;
myPrintDialog.Document = printDocument1;
printDocument1.PrintController = new StandardPrintController();
printDocument1.Print();
}
printDocument1.Dispose();


You can also find some sample source code to print the content of a Panel in the following link.

http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/675b8a1b-fb03-4658-964e-56a417c08e37/
  James H replied to kshama parashar
11-Oct-11 03:11 AM
Hi Please refer this link for more information
http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx

Hope this will help you :-)
  dipa ahuja replied to kshama parashar
11-Oct-11 03:17 AM
Untitled document
Use the code:
 
private void btnPrint_Click(object sender, EventArgs e)
{
   Graphics g1 = this.CreateGraphics();
   Image MyImage = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height, g1);
   Graphics g2 = Graphics.FromImage(MyImage);
   IntPtr dc1 = g1.GetHdc();
   IntPtr dc2 = g2.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
   g1.ReleaseHdc(dc1);
   g2.ReleaseHdc(dc2);
   MyImage.Save(@"c:\PrintPage.jpg", ImageFormat.Jpeg);
   FileStream fileStream = new FileStream(@"c:\PrintPage.jpg", FileMode.Open, FileAccess.Read);
   StartPrint(fileStream, "Image");
   fileStream.Close();
   if (System.IO.File.Exists(@"c:\PrintPage.jpg"))
   {
     System.IO.File.Delete(@"c:\PrintPage.jpg");
   }
}
http://www.c-sharpcorner.com/UploadFile/srajlaxmi/PrintingWindowsForm01182008021239AM/PrintingWindowsForm.aspx
Create New Account
help
Framework Hallo, kann mir jemand sagen, warum das unten aufgef = FChrte Beispiel zum Drucken in Visual Studio nicht funktioniert? Ist aus einem Buch abgeschrieben. . . . = 3D) oder gibt es vielleicht eine k = FCrzere Visual Basic Anweisung daf = FCr? Private Sub Pct_Drucken_Click(ByVal sender As System.Object, ByVal e As End Sub Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim gr As Graphics = 3D e.Graphics Dim ps As Printing.PageSettings Brushes.Black, Rectangle.Round (printrect)) fnt.Dispose() End Sub VB - German Discussions System.Drawing.Printing.PrintPageEventArgs (1) Visual Studio (1) PrintDocument1.PrintPage (1) Printing.PageSettings (1) System.EventArgs (1) VB (1) Rectangle.Round (1 german.entwickler.dotnet.vb Zu Deinem Problem schau Dir vielleicht erst mal www.gssg.de -> Visual Basic -> VB.net -> Print Sample Drucken mit dem Printdocument - Objekt an. Dieses Beispiel druckt div
Print the page pdoc-> Print(); } else MessageBox::Show("Print cancelled", "Information"); } void PrintAPage(Object^ pSender, PrintPageEventArgs^ pe) { } If I put the following code inside the empty function (PrintAPage)I will be pl-> p1.Y, pl-> p2.X, pl-> p2.Y); } - - Thanks Allen .NET Discussions PrintPageEventHandler (1) Visual Studio 2008 (1) PrintPageEventArgs (1) File.ReadAllText (1) PrintDialog (1) ReadAllText (1) EventArgs (1) PrintToolStripMenuItem (1) Hi Allen, You windows.forms.dll : see declaration of 'System::Windows::Forms::Control' 1> c: \ users \ allen \ documents \ visual studio 2008 \ projects \ timetracking \ timetracking \ Form1.h(248) : warning C4832: token '.' is illegal after UDT 'System 0.50727 \ mscorlib.dll : see declaration of 'System::IO::File' 1> c: \ users \ allen \ documents \ visual studio 2008 \ projects \ timetracking \ timetracking \ Form1.h(248) : error C2275: 'System::IO::File' : illegal use of
How can i get the print out of crystal report using visual studio .Net I'm using crystal report for my application, i do want to get the lines) { lines[i++] = s.TrimEnd(trimParam); } } / / OnPrintPage private void OnPrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { int x = e.MarginBounds.Left; int y = e.MarginBounds.Top; Brush brush = new SolidBrush
ReportViewer does not show Print option. Dear all, I am making Asp.net , C#(Visual Studio 2005) and SQl2000. I am trying to generate report using reportviewer. i managed to success Exception End Try End Sub Public Sub PrintPage( ByVal sender As Object , ByVal ev As PrintPageEventArgs) Dim pageImage As New Metafile(m_streams(m_currentPageIndex)) ev.Graphics.DrawImage(pageImage, ev.PageBounds) m_currentPageIndex + = 1
token / ticket by accessing data from database in sql2008 in asp.net i am using visual studio 2010 using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; using new PrintPageEventHandler (pd_PrintPage); pd.Print(); } finally { streamToPrint.Close(); } } catch ( Exception ex) { } } void pd_PrintPage( object sender, PrintPageEventArgs ev) { float linesPerPage = 0; float yPos = 0; int count = 0; float leftMargin = ev.MarginBounds.Left