0

I am printing group box but it is not properly printing. How to print and fit it in A4 size paper. Here is my code

Private Sub printbtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles printbtn.Click
    PrintDialog1.Document = PrintDocument1 'PrintDialog associate with PrintDocument.
    If PrintDialog1.ShowDialog() = DialogResult.OK Then
        PrintDocument1.Print()
    End If
End Sub

Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Dim x As Single = e.MarginBounds.Left
    Dim y As Single = e.MarginBounds.Top
    Dim bmp As New Bitmap(Me.GroupBox1.Width, Me.GroupBox1.Height)
    Me.GroupBox1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.GroupBox1.Width, Me.GroupBox1.Height))
    e.Graphics.DrawImage(DirectCast(bmp, Image), x, y)
End Sub

and getting output like this click

R.D
  • 3
  • 3
  • You need to either [resize the image](https://stackoverflow.com/a/3494927/4934172) to fit the width of the page and/or [change the orientation of the page to landscape](https://stackoverflow.com/a/19137591/4934172). – 41686d6564 stands w. Palestine Oct 20 '19 at 11:40

2 Answers2

0

Here the code:

Dim WithEvents PrintDocument1 As Printing.PrintDocument = New Printing.PrintDocument

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    PrintDocument1.Print()
End Sub


Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
    Dim x As Single = e.MarginBounds.Left
    Dim y As Single = e.MarginBounds.Top
    Dim bmp As New Bitmap(Me.GroupBox1.Width, Me.GroupBox1.Height)
    Me.GroupBox1.DrawToBitmap(bmp, New Rectangle(0, 0, Me.GroupBox1.Width, Me.GroupBox1.Height))

    'Get the A4 size 
    Dim limitX As Integer = e.PageBounds.Width
    'use this to reduce your screenshot for the A4 format page
    Dim reduceMe As Double = limitX / Me.GroupBox1.Width


    Dim reducedBmp As New Bitmap(bmp, CInt(Me.GroupBox1.Width * reduceMe), CInt(Me.GroupBox1.Height * reduceMe))
    e.Graphics.DrawImage(reducedBmp, x, y)

End Sub
G3nt_M3caj
  • 2,497
  • 1
  • 14
  • 16
0

How about this one:

Dim srcRect As Rectangle = GroupBox1.ClientRectangle
Dim desRect As New Rectangle(e.MarginBounds.X, e.MarginBounds.Y, e.MarginBounds.Width, GroupBox1.Height)
Dim bmp As New Bitmap(srcRect.Width, srcRect.Height)

GroupBox1.DrawToBitmap(bmp, srcRect)

e.Graphics.SmoothingMode = SmoothingMode.HighQuality

e.Graphics.DrawImage(bmp, desRect, srcRect, GraphicsUnit.Pixel)

bmp.Dispose()

Good luck.