Friday, July 3, 2009

PrintDocument and PrintPreview Components and Builing a Reporting Tool

PrintDocument Class defines an object that sends output to a printer used in Windows Forms Application.
First create a Graphics object which essentialy is a drawing surface using the PrintEvenArgs object which is an argument of PrintDocument's PrintPage event.

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Shalvin", Font, Brushes.Blue, 50, 50);
g.DrawLine(Pens.Red, 70, 70, 150, 70);

g.DrawRectangle(Pens.Purple, 100, 100, 105, 105);

g.DrawEllipse(Pens.Peru, 125, 125, 130, 130);

g.DrawPie(Pens.PeachPuff, 150, 150, 200, 200, 0, 90);
g.DrawPie(Pens.PaleGreen, 150, 150, 200, 200, 90, 45);
g.DrawPie(Pens.Orange, 150, 150, 200, 200, 135, 135);
g.FillPie(Brushes.AntiqueWhite, 150, 150, 200, 200, 270, 90);

g.FillRectangle(Brushes.Beige, 300, 300, 325, 325);
}

private void Form1_Load(object sender, EventArgs e)
{
printPreviewDialog1.Document = printDocument1;
}

private void btnPrint_Click(object sender, EventArgs e)
{
printPreviewDialog1.ShowDialog();
}





















Reporting Tool
Application development is rarely DrawLine or DrawEllipse. Let's see how to develop a reporting tool with PrintDocument class.

using System.Data.SqlClient;

SqlConnection cnn;
SqlCommand cmd;
SqlDataReader dr;

private void Form1_Load(object sender, EventArgs e)
{
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Northwind");
cnn.Open();
cmd = new SqlCommand("select * from Categories", cnn);
dr = cmd.ExecuteReader();
printPreviewDialog1.Document = printDocument1;
}


private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Graphics g = e.Graphics;
g.DrawString("Category Id \t\t Category Name \t\t Description", Font, Brushes.Black, 50, 50 );
g.DrawString("___________ \t\t _____________ \t\t ___________", Font, Brushes.Black, 50, 55);
//g.DrawLine(Pens.DarkSlateBlue,50,65,600,65);
int y = 70;
while (dr.Read())
{
g.DrawString(dr["CategoryId"].ToString()+"\t\t\t"+ dr["CategoryName"].ToString()+ "\t\t" + dr["Description"].ToString(), Font,Brushes.Black, 60, y );
y += 20;
}
}


No comments:

Post a Comment