vb.netwinformsprintdocument

Print images on multiple pages


I have barcode images in a folder and I want to print them like in the image below. But the problem is I can't make the rest of the image go to the next page.

In this situation, I have 22 images, but the paper fits only 20 to 21 (the last image is cut by the margin). My question is how do I make the rest 20s and 20s if I got many images to the next pages?

barcode images

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage

    Dim extensions As New List(Of String)
    extensions.Add("*.jpg")
    ' And so on, until all are in...

    Dim fileCount As Integer
    For i As Integer = 0 To extensions.Count - 1
        fileCount += Directory.GetFiles(Application.StartupPath & "\temp\", extensions(i), SearchOption.AllDirectories).Length
    Next

    Dim imgPictures(fileCount) As Image

    For i As Integer = 1 To fileCount
        imgPictures(i) = Bitmap.FromFile(Application.StartupPath & "\temp\" & i & ".jpg")
        e.Graphics.DrawImage(imgPictures(i), 50, 50 * i)
        If i = 20 Then
            e.HasMorePages = True
        ElseIf i = fileCount Then
            e.HasMorePages = False
        End If
    Next
End Sub

Solution

  • After hours of trying, finally it worked, shout out to jmcilhinney, big help

    Dim recordCount As Integer
    
    Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim lineCount As Integer
        Dim extensions As New List(Of String)
        extensions.Add("*.jpg")
        ' And so on, until all are in...
    
        Dim fileCount As Integer
        For i As Integer = 0 To extensions.Count - 1
            fileCount += Directory.GetFiles(Application.StartupPath & "\temp\", extensions(i), SearchOption.AllDirectories).Length
        Next
    
        Dim imgPictures(fileCount) As Image
        For i As Integer = 1 To fileCount
            recordCount += 1
            lineCount += 1
            imgPictures(recordCount) = Bitmap.FromFile(Application.StartupPath & "\temp\" & recordCount & ".jpg")
            e.Graphics.DrawImage(imgPictures(recordCount), 50, 50 * i)
            If lineCount >= 20 Then
                Exit For
            ElseIf recordCount = fileCount Then
                Exit For
            End If
        Next
        If recordCount = fileCount Then
            e.HasMorePages = False
        ElseIf lineCount = 20 Then
            e.HasMorePages = True
        End If
    End Sub
    
    Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
        recordCount = 0
    End Sub