Using Printer to print all the records of DataRepeater

One question being asked about DataRepeater in the MSDN forum is that how to print all the populated records from DataRepeater. If the number of the records is small enough to fit into the view of the DataRepeater, this would be a very simple task: use PrintForm component to print the form that contains the DataRepeater. However, the number of records is usually large and records cannot be fit in one page. To print all the records including the records that are out of view, Printer component (another VB Power Packs component) can be used.

For example, let’s say I have a DataRepeater control and a “Print” button on a Form.

Then I add a “Click” event handler for the Print button. In the Click event handler, I’ll print all the records. The basic idea here is to go through all the DataRepeater items. For each DataRepeater item, set it as the current item of the DataRepeater. This is to make the item scroll into the view. Then I draw the item to a bitmap by using Control.DrawToBitmap. And finally I print the bitmap to the printer.

This is the code:


    Private Sub PrintButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintButton.Click
        If Me.DataRepeater1.ItemCount > 0 Then
            ' Define a VB Power Packs Printer object
            Dim printer As New Printer()

            Dim sz As Size = Me.DataRepeater1.CurrentItem.ClientSize
            Dim w As Integer = sz.Width
            Dim h As Integer = sz.Height

            Dim bm As New Bitmap(w, h)

            Dim x = 0
            Dim y = 100

            Dim n As Integer = Me.DataRepeater1.ItemCount
            For i As Integer = 1 To n
                ' Set item i be the current item so that it can be visible
                Me.DataRepeater1.CurrentItemIndex = i - 1

                ' Paint the content of the current DataRepeater item to a bitmap
                Dim item As DataRepeaterItem = Me.DataRepeater1.CurrentItem
                item.DrawToBitmap(bm, item.ClientRectangle)

                ' if y coordinate > height of the page, start a new page
                ' assuming one page can show 15 items
                If y + h * 15 + 100 > printer.ScaleHeight Then
                    y = 100
                End If

                ' Print the bitmap to the printer
                printer.PaintPicture(bm, x, y)

                ' Calculate the next left,top position
                y += h * 15

        End If
    End Sub

You may need to import following namespace if you haven’t done so:

Imports Microsoft.VisualBasic.PowerPacks
Imports Microsoft.VisualBasic.PowerPacks.Printing.Compatibility.VB6
Related topic:  DataRepeater Control for Windows Forms

Comments (1)

  1. 11x17printer says:

    great tips. I need it to print from Datarepeater.

Skip to main content