Wednesday, August 1, 2007

Printing Form Controls in .NET

I got a project that ordered me to print out a form in .NET. There is a simple way to print out form. We can use DrawToBitmap methode in each .NET controls to converts forms become bitmap, then move it to printer graphics objects.
To print out, we need three other controls: PageSetupDialog, PrintDocument, and PrintPreviewDialog.

We can handle PrintPage events in PrintDocument to draw form and controls to printer graphics object:

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim r As Rectangle = New Rectangle(e.MarginBounds.Location,Me.DisplayRectangle.Size)
e.Graphics.Clip = New Region(e.MarginBounds)
Dim a As New Bitmap(r.Width, r.Height, e.Graphics)
'Draw to bitmap
Me.DrawToBitmap(a, r)
'Draw bitmap to printer graphics object
e.Graphics.DrawImage(a, r)
e.Graphics.ResetClip()
a = Nothing
'continue print other page or not
e.HasMorePages = False
End Sub

Then print function:

Private Sub Print()
'Seting Page Setup
PageSetupDialog1.PageSettings.Margins.Top = 0 PageSetupDialog1.PageSettings.Margins.Bottom = 0
PageSetupDialog1.PageSettings.Margins.Left = 0
PageSetupDialog1.PageSettings.Margins.Right = 0
Dim pdOld As Printing.PrintDocument = Me.PrintPreviewDialog1.Document
Me.PrintPreviewDialog1.Document = Me.PrintDocument1
Me.PrintPreviewDialog1.ShowDialog()
Me.PrintPreviewDialog1.Document = pdOld
End Sub

No comments: