Monday, 9 April 2012

Coding For Printing A Form In VB.net


Public Class Form1
    Dim withd As Integer = Print.Width
    Dim higt As Integer = Print.Height
    Dim bm As New Bitmap(withd, higt)
    Private Function GetFormImage(ByVal IncluseFormBorders As Boolean) As Bitmap
        ' Draw the form onto the bitmap.
        Me.DrawToBitmap(bm, New Rectangle(0, 0, withd, higt))

        ' If we want the borders, return the bitmap.
        If IncluseFormBorders Then Return bm

        ' Make a smaller bitmap without borders.
        withd = Print.ClientSize.Width
        higt = Print.ClientSize.Height
        Dim bm2 As New Bitmap(withd, higt)

        ' Get the offset from the window's corner to its client
        ' area's corner.
        Dim pt As New Point(0, 0)
        pt = PointToScreen(pt)
        Dim dx As Integer = pt.X - Print.Left
        Dim dy As Integer = pt.Y - Print.Top

        ' Copy the part of the original bitmap that we want
        ' into the bitmap.
        Dim gr As Graphics = Graphics.FromImage(bm2)
        gr.DrawImage(bm, 0, 0, New Rectangle(dx, dy, withd, higt), _
          GraphicsUnit.Pixel)
        Return bm2
    End Function

    Private Function PrintFormImage()
        PrintDocument1.Print()

    End Function


    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Print.Show()
        Me.Hide()
        GetFormImage(True)
        PrintFormImage()
    End Sub

   
    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim g As Graphics
        g = e.Graphics
        g.DrawImage(bm, 0, 0)
        g.Dispose()
        e.HasMorePages = False
    End Sub

 
End Class