Private Sub pDoc_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles pDoc.PrintPage
'Determine the printable area based on the page settings
Dim pSettings As PageSettings = pDoc.DefaultPageSettings
Dim pOrigin As Point = New Point(pSettings.Margins.Left, pSettings.Margins.Top)
Dim pSize As Size = New Size(pSettings.PaperSize.Width - (pSettings.Margins.Left + pSettings.Margins.Right), _
pSettings.PaperSize.Height - (pSettings.Margins.Top + pSettings.Margins.Bottom))
' If the user selected Landscape mode, swap the printing area height
' and width.
If pDoc.DefaultPageSettings.Landscape Then
Dim intTemp As Int32
intTemp = pSize.Height
pSize.Height = pSize.Width
pSize.Width = intTemp
End If
'We have to determine the proper scaling based on the available print area to maintain the aspect ratio
Dim wRatio As Single = pSize.Width / ImageToPrint.Width
Dim hRatio As Single = pSize.Height / ImageToPrint.Height
Dim ScaleToWidth As Boolean = False
Dim ScaleToHeight As Boolean = False
If wRatio < hRatio Then
'Scale to the width ratio
ScaleToWidth = True
Else
'Scale to the height ratio
ScaleToHeight = True
End If
Dim sizePrint As Size
If ImageToPrint.Width < pSize.Width AndAlso ImageToPrint.Height < pSize.Height Then
sizePrint = New Size(ImageToPrint.Width, ImageToPrint.Height)
Else
If ScaleToWidth Then
sizePrint = New Size(ImageToPrint.Width * wRatio, ImageToPrint.Height * wRatio)
ElseIf ScaleToHeight Then
sizePrint = New Size(ImageToPrint.Width * hRatio, ImageToPrint.Height * hRatio)
End If
End If
'Let's center the image just for fun.
Dim loc As Point
loc = New Point(pOrigin.X + ((pSize.Width - sizePrint.Width) / 2), pOrigin.Y + ((pSize.Height - sizePrint.Height) / 2))
e.Graphics.DrawImage(ImageToPrint, New Rectangle(loc, sizePrint))
'These lines are not needed. Just here to demonstrate the Margin settings.
Dim penBorder As New Pen(Color.Blue)
penBorder.DashStyle = Drawing2D.DashStyle.Dash
e.Graphics.DrawRectangle(penBorder, New Rectangle(pOrigin.X, pOrigin.Y, pSize.Width, pSize.Height))
End Sub