You need to use the 'DefaultPageSettings.Margins' method, full explanation and sample code at -
PageSettings.Margins Property[
^]
Your code will look similar to -
Private Sub TSPrint_Click(sender As Object, e As EventArgs) Handles TSPrint.Click
PrintDialog1.Document = PrintDocument1
If PrintDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
PrintDocument1.DefaultPageSettings.Margins = New System.Drawing.Printing.Margins(50, 50, 50, 50)
PrintDocument1.Print()
End If
End Sub
Make sure to update your 'PrintDocument1.PrintPage' event handler as well to account for the newly set margins when drawing the content to be printed that will handle the text that exceeds the available space within the margins by wrapping it to a new line.
Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim graphics As Graphics = e.Graphics
Dim font As New Font("Arial", 12)
Dim brush As New SolidBrush(Color.Black)
Dim leftMargin As Integer = e.MarginBounds.Left
Dim topMargin As Integer = e.MarginBounds.Top
Dim text As String = "This is my text I want to print which might exceeds the right margin if I am not carefull, with this code I can wrap the long text to a new line without it being cutt off at the end................!"
Dim availableWidth As Integer = e.MarginBounds.Width
Dim availableHeight As Integer = e.MarginBounds.Height
Dim textSize As SizeF = graphics.MeasureString(text, font)
If textSize.Width <= availableWidth AndAlso textSize.Height <= availableHeight Then
graphics.DrawString(text, font, brush, leftMargin, topMargin)
Else
Dim truncatedText As String = TruncateTextToFit(text, font, availableWidth)
graphics.DrawString(truncatedText, font, brush, leftMargin, topMargin)
End If
End Sub
Private Function TruncateTextToFit(text As String, font As Font, availableWidth As Integer) As String
Dim textSize As SizeF = graphics.MeasureString(text, font)
While textSize.Width > availableWidth AndAlso text.Length > 0
text = text.Substring(0, text.Length - 1)
textSize = graphics.MeasureString(text, font)
End While
Return text
End Function