Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » GDI+ & Graphics » Printing out your W2 Form using C# and .NET

Printing out your W2 Form using C# and .NET

This article covers a fairly practical aspect of using a computer - dealing with forms. The concepts in this article can be used to create any Form Application so that you can design forms that you can Fill Out, Open, Save, Print and Print Preview.

Author Rank :
Page Views : 60779
Downloads : 878
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
W2FormMG.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


If you are a C# programmer, before you run out and buy that latest version of your favorite tax program, you may want to consider this useful article on form creation.  This article covers a fairly practical aspect of using a computer - dealing with forms.  The concepts in this article can be used to create any Form Application so that you can design forms that you can Fill Out, Open, Save, Print and Print Preview.



Fig 1.0 - PrintPreview of the W2 Form

Below is the simple UML design of our W2 Form Filler Application:

Fig 1.1 - UML Doc/View Design of W2 Form App reverse engineered using WithClass 2000

The first step to creating the form is to scan in the Form and convert it to a .gif file.  You can also get most forms these days electronically from the .gov sites that supply them.  Once you've got the form in a .gif (or jpeg or whatever),  you can apply it to your form as an image background.   Simply set the forms BackgroundImage property to the gif or jpeg file that you scanned in.  Now you are ready to set up the forms edit fields.  This form only uses TextBoxes and CheckBoxes.  The TextBoxes overlay the whitespaces for all the places you would normally fill in the form and have names that are appropriate for the particular field on the form. The property window for a TextBox is shown below: 

 

Fig 1.2 - Property window of a TextBox in the Form

The BorderStyle for all textboxes are set to none and the background color(BackColor) is set to the color of the form.  

With Checkboxes you need to do a bit of extra work.  Since you can't eliminate the border of a checkbox, we needed to go into the jpeg file of the form and remove the checkboxes, so we could place the real checkboxes in the form.  You can us MSPaint and the little eraser utility to do this easily enough.  The properties of the checkboxes are shown below:

Fig 1.3 - Property window of a Checkbox in the Form

You need to choose the FlatStyle to be Flat for the Checkbox, so the checkbox looks like a checkbox on a typical government form rather than that fun 3d look.

Once we've put all our window controls on the form, we need to set the tab order.  This is done by clicking on the form and going into the View menu, then choosing Tab Order.

Fig 1.4 - Choosing Tab Order from the View Menu

Once you've chosen the Tab Order menu item, you'll notice your form light up with a bunch of boxed numbers.  Click in each box in the order you want users to traverse your form.

Now we can get down to some good old-fashioned C# coding (well not that old-fashioned yet ;-).  This application handles many aspects of C# .NET coding (serialization, printing, print preview).  We are only going to talk about printing in detail in this article, because, well, it's the most interesting.  Printing requires that you have a PrintDocument object added to the form.  We've also added a PrintDialog object and a PrintPreview Dialog Object.  It's much less expensive and time consuming to test printing in the print preview window so you should try to get this working first.  The PrintPreview code is shown below:

private void PreviewMenu_Click(object sender, System.EventArgs e)
{
PrintPreviewDialog printPreviewDialog1 =
new PrintPreviewDialog();
printPreviewDialog1.Document =
this.printDocument1 ; // Attach PrintDocument to PrintPreview Dialog
printPreviewDialog1.FormBorderStyle = FormBorderStyle.Fixed3D ;
printPreviewDialog1.SetBounds(20, 20,
this.Width, this.Height); // enlarge dialog to show the form
printPreviewDialog1.ShowDialog();
}

Listing 1 - Code for Print Preview

Both printing and print preview use the same event to print the form.  They both use the PrintPage event from the print document.   All printing code is performed in this routine.  The printing is done into a Graphics object which is passed into the print page event arguement:

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
DrawAll(e.Graphics);
// Pass the Graphics Object (or better known as the Device Context) to the Draw routine
} 

Listing 2 - Code For Printing a Page

The DrawAll routine is in two parts.  The first part prints the image scaled to fit on the printed page.  The second part cycles through all the controls and prints the text or check mark contained within each control.  The program uses the position of the textboxes and checkboxes, along with the scaling factors, to position the filled-in information on the form:

private void DrawAll(Graphics g)
{
// Create the source rectangle from the BackgroundImage Bitmap Dimensions
RectangleF srcRect = new Rectangle(0, 0, this.BackgroundImage.Width, BackgroundImage.Height);
// Create the destination rectangle from the printer settings holding printer page dimensions
int nWidth = printDocument1.PrinterSettings.DefaultPageSettings.PaperSize.Width;
int nHeight = printDocument1.PrinterSettings.DefaultPageSettings.PaperSize.Height;
RectangleF destRect =
new Rectangle(0, 0, nWidth, nHeight/2);
// Draw the image scaled to fit on a printed page
g.DrawImage(this.BackgroundImage, destRect, srcRect, GraphicsUnit.Pixel);
// Determine the scaling factors of each dimension based on the bitmap and the printed page dimensions
// These factors will be used to scale the positioning of the contro contents on the printed form
float scalex = destRect.Width/srcRect.Width;
float scaley = destRect.Height/srcRect.Height;
Pen aPen =
new Pen(Brushes.Black, 1);
// Cycle through each control. Determine if it's a checkbox or a textbox and draw the information inside
// in the correct position on the form
for (int i = 0; i < this.Controls.Count; i++)
{
// Check if its a TextBox type by comparing to the type of one of the textboxes
if (Controls[i].GetType() == this.Wages.GetType())
{
// Unbox the Textbox
TextBox theText = (TextBox)Controls[i];
// Draw the textbox string at the position of the textbox on the form, scaled to the print page
g.DrawString(theText.Text, theText.Font, Brushes.Black, theText.Bounds.Left*scalex, theText.Bounds.Top * scaley, new StringFormat());
}
if (Controls[i].GetType() == this.RetirementPlanCheck.GetType())
{
// Unbox the Checkbox
CheckBox theCheck = (CheckBox)Controls[i];
// Draw the checkbox rectangle on the form scaled to the print page
Rectangle aRect = theCheck.Bounds;
g.DrawRectangle(aPen, aRect.Left*scalex, aRect.Top*scaley, aRect.Width*scalex, aRect.Height*scaley);
// If the checkbox is checked, Draw the x inside the checkbox on the form scaled to the print page
if (theCheck.Checked)
{
g.DrawString("x", theCheck.Font, Brushes.Black,theCheck.Left*scalex + 1, theCheck.Top*scaley + 1,
new StringFormat());
}
}
}
}

Listing 3 - Drawing routine for drawing the form to the printer or the print preview

The actual printing onto a printer begins in the routine below.  This routine brings up the print dialog and if the user accepts, it prints the form onto the printer using the PrintPage event previously discussed:

private void menuItem2_Click(object sender, System.EventArgs e)
{
// Attach the PrintDialog to the PrintDocument Object
printDialog1.Document = this.printDocument1;
// Show the Print Dialog before printing
if (printDialog1.ShowDialog() == DialogResult.OK)
{
this.printDocument1.Print(); // Print the Form
}
}
 

Listing 4 - Printing Menu Event for printing to the printer

Serialization

You may want to browse through the rest of the code to see how serialization is done.  This project uses a Document/View archictecture.  The W2Document Class handles persistence for the form(reading/writing) and the W2Document is made serializable by the [Serializable()] attribute inside the class.  The read and write routines use the BinaryFormatter Class  in combination with the File Class to serialize and deserialize the information extracted from the form.

Improvements

I think that the project could be made much more useful if the code was ported to the Web Form.  Then someone could create an application with C# running code-behind that outputted the Web Form information into a database rather than a file.  Then maybe government, hospitals, insurance companies, law firms and all other businesses dealing with "form-bureaucracy" could get more easily organized ;-) through .NET.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.