Printing out your W2 Form using C# and .NET

Printing out your W2 Form using C# and .NET
Submitted ByUser LevelDate of Submission
Mike GoldIntermediate08/07/2001

Source Code:

Fig 1.0 - PrintPreview of the W2 Form

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.  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:

privatevoid 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

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:

privatevoid 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:

privatevoid 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, 

     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:

privatevoid 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


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.


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.

About the Author:Mike Gold is President of Microgold Software Inc. and Creator of WithClass 2000 a UML Design Tool for C#.   In the last few years Mike has consulted for companies such as Merrill Lynch and Chase Manhattan Bank in New York.  He is been active in developing Visual C++ Applications for 10 years and looks forward to the possibilities in C#. You can reach him at

  • 0
  • 0
  • 0
  • 一键三连
  • 扫一扫,分享海报

<div style="color:rgba(0,0,0,.75);"> <span style="color:#4d4d4d;"> </span> <div style="color:rgba(0,0,0,.75);"> <span style="color:#4d4d4d;"> </span> <div style="color:rgba(0,0,0,.75);"> <div style="color:rgba(0,0,0,.75);"> <span style="color:#4d4d4d;">当前课程中商城项目的实战源码是我发布在 GitHub 上的开源项目 newbee-mall (新蜂商城),目前已有 6300 多个 star,</span><span style="color:#4d4d4d;">本课程是一个 Spring Boot 技术栈的实战类课程,课程共分为 3 大部分,前面两个部分为基础环境准备和相关概念介绍,第三个部分是 Spring Boot 商城项目功能的讲解,让大家实际操作并实践上手一个大型的线上商城项目,并学习到一定的开发经验以及其中的开发技巧。<br /> 商城项目所涉及的功能结构图整理如下:<br /> </span> </div> <div style="color:rgba(0,0,0,.75);">   </div> <div style="color:rgba(0,0,0,.75);"> <p style="color:#4d4d4d;"> <img alt="modules" src=",png" /> </p> </div> <p style="color:rgba(0,0,0,.75);"> <strong><span style="color:#e53333;">课程特色</span></strong> </p> <p style="color:rgba(0,0,0,.75);">   </p> <div style="color:rgba(0,0,0,.75);">   </div> <div style="color:rgba(0,0,0,.75);"> <ul> <li> 对新手开发者十分友好,无需复杂的操作步骤,仅需 2 秒就可以启动这个完整的商城项目 </li> <li> 最终的实战项目是一个企业级别的 Spring Boot 大型项目,对于各个阶段的 Java 开发者都是极佳的选择 </li> <li> 实践项目页面美观且实用,交互效果完美 </li> <li> 教程详细开发教程详细完整、文档资源齐全 </li> <li> 代码+讲解+演示网站全方位保证,向 Hello World 教程说拜拜 </li> <li> 技术栈新颖且知识点丰富,学习后可以提升大家对于知识的理解和掌握,可以进一步提升你的市场竞争力 </li> </ul> </div> <p style="color:rgba(0,0,0,.75);">   </p> <p style="color:rgba(0,0,0,.75);"> <span style="color:#e53333;">课程预览</span> </p> <p style="color:rgba(0,0,0,.75);">   </p> <div style="color:rgba(0,0,0,.75);">   </div> <div style="color:rgba(0,0,0,.75);"> <p style="color:#4d4d4d;"> 以下为商城项目的页面和功能展示,分别为: </p> </div> <div style="color:rgba(0,0,0,.75);"> <ul> <li> 商城首页 1<br /> <img alt="" src="" /> </li> <li> 商城首页 2<br /> <img alt="" src="" /> </li> <li>   </li> <li> 购物车<br /> <img alt="cart" src=",png" /> </li> <li> 订单结算<br /> <img alt="settle" src=",png" /> </li> <li> 订单列表<br /> <img alt="orders" src=",png" /> </li> <li> 支付页面<br /> <img alt="" src="" /> </li> <li> 后台管理系统登录页<br /> <img alt="login" src=",png" /> </li> <li> 商品管理<br /> <img alt="goods" src=",png" /> </li> <li> 商品编辑<br /> <img alt="" src="" /> </li> </ul> </div> </div> </div> </div>
<p style="color:#666666;"> <span style="font-size:14px;">本门课程重实战,将基础知识拆解到项目里,让你在项目情境里学知识。</span> </p> <p style="color:#666666;"> <span style="font-size:14px;">这样的学习方式能让你保持兴趣、充满动力,时刻知道学的东西能用在哪、能怎么用。</span> </p> <p style="color:#666666;"> <span style="font-size:14px;">平时不明白的知识点,放在项目里去理解就恍然大悟了。</span> </p> <p style="color:#666666;"> <span></span> </p> <p style="color:#666666;"> <span style="font-size:14px;"> </span> </p> <p style="color:#666666;"> <span style="color:#FF0000;font-size:14px;"><strong>一、融汇贯通</strong></span> </p> <p style="color:#666666;"> <span style="font-size:14px;">本视频采用了前后端分离的开发模式,前端使用Vue.js+Element UI实现了Web页面的呈现,后端使用Python 的Django框架实现了数据访问的接口,前端通过Axios访问后端接口获得数据。在学习完本章节后,真正理解前后端的各自承担的工作。</span> </p> <p style="color:#666666;"> <span style="font-size:14px;"> </span> </p> <p style="color:#666666;"> <span style="color:#FF0000;font-size:14px;"><strong>二、贴近实战</strong></span> </p> <p style="color:#666666;"> <span style="font-size:14px;">本系列课程为练手项目实战:学生管理系统v4.0的开发,项目包含了如下几个内容:项目的总体介绍、基本功能的演示、Vuejs的初始化、Element UI的使用、在Django中实现针对数据的增删改查的接口、在Vuejs中实现前端增删改查的调用、实现文件的上传、实现表格的分页、实现导出数据到Excel、实现通过Excel导入数据、实现针对表格的批量化操作等等,所有的功能都通过演示完成、贴近了实战</span> </p> <p style="color:#666666;"> <span style="font-size:14px;"> </span> </p> <p style="color:#666666;"> <span style="color:#FF0000;font-size:14px;"><strong>三、课程亮点</strong></span> </p> <p style="color:#666666;"> <span style="font-size:14px;">在本案例中,最大的亮点在于前后端做了分离,真正理解前后端的各自承担的工作。前端如何和后端交互</span> </p> <p style="color:#666666;"> <span style="font-size:14px;"> </span> </p> <p style="color:#666666;"> <span style="color:#FF0000;font-size:14px;"><strong>适合人群:</strong></span> </p> <p style="color:#666666;"> <span style="font-size:14px;">1、有Python语言基础、web前端基础,想要深入学习Python Web框架的朋友;</span> </p> <p style="color:#666666;"> <span style="font-size:14px;">2、有Django基础,但是想学习企业级项目实战的朋友;</span> </p> <p style="color:#666666;"> <span style="font-size:14px;">3、有MySQL数据库基础的朋友</span> </p> <p style="color:#666666;"> <span style="font-size:14px;"> </span> </p> <p style="color:#666666;"> <span style="font-size:14px;"><img alt="" src="" /><br /> </span> </p> <p style="color:#666666;"> <span style="font-size:14px;"><br /> </span> </p>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
钱包余额 0