I have a groupbox that has some controls in it and i want to send it to printer.
I have this code thats builds the bmp file from the groupbox. How can i sent it to printer at button click?
Private Sub Doc_PrintPage(sender As Object, e As PrintPageEventArgs)
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
I have in button click event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim doc As New PrintDocument()
doc = Doc_PrintPage()
Dim dlgSettings As New PrintDialog()
dlgSettings.Document = doc
If dlgSettings.ShowDialog() = DialogResult.OK Then
doc.Print()
End If
End Sub
Final working code after advices:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BMP = New Bitmap(GroupBox1.Width, GroupBox1.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)
GroupBox1.DrawToBitmap(BMP, New Rectangle(0, 0, GroupBox1.Width, GroupBox1.Height))
Dim pd As New PrintDocument
Dim pdialog As New PrintDialog
AddHandler pd.PrintPage, (Sub(s, args)
args.Graphics.DrawImage(BMP, 0, 0)
args.HasMorePages = False
End Sub)
pdialog.ShowDialog()
pd.PrinterSettings.PrinterName = pdialog.PrinterSettings.PrinterName
pd.Print()
End Sub
The idea is that you have a PrintDocument
object, you call its Print
method, it raises its PrintPage
event, you handle that event and in the handler method you use GDI+ to draw whatever is to be printed. So, you need to get rid of this line:
doc = Doc_PrintPage()
What could that possibly be doing? You are trying to assign the result of a method to a PrintDocument
variable. In order for that to be meaningful, the method would have to return a PrintDocument
object, which it doesn't. What you need to do is register that method to handle the PrintPage
event of your PrintDocument
:
AddHandler doc.PrintPage, AddressOf Doc_PrintPage
If you do that then you need to remove the handler as well. A better option would be to add all your printing objects to the form in the designer and then create a PrintPage
event handler for the PrintDocument
just as you would create event handlers for a Button
or a TextBox
.
For more info on printing, you may find this useful.