Search code examples
vb.netprintingdrawstringprintdocument

Margin in VB.NET printing


I am trying to print a receipt on 58mm thermal printing with the use of vb.net and Graphics.DrawString of vb.net but it is leaving some space at the beginning. I have also tried by giving the x coordinates values as 0 and negative, in such cases the first case is either printing half or discarded sometimes.

The code is as below

    Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click

    PrintDialog1.Document = PrintDocument1 'PrintDialog associate with PrintDocument.

    If PrintDialog1.ShowDialog() = DialogResult.OK Then
        PrintDocument1.Print()
    End If
End Sub



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

    Dim printFont = New Font("Calligraphr", 24.8, FontStyle.Regular)

    Dim printBold = New Font("Calligraphr", 26, FontStyle.Bold)
    e.Graphics.DrawString("C", printFont, Brushes.Black, New Point(0, 50))
    e.Graphics.DrawString("I", printFont, Brushes.Black, New Point(-6, 60))
    e.Graphics.DrawString("T", printFont, Brushes.Black, New Point(6, 60))
    e.Graphics.DrawString("Y", printFont, Brushes.Black, New Point(12, 60))

   End Sub

Photo of Printing of above code


Solution

  • Try put in the size of the paper you are handling before printing such as

    Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
    
        PrintDoc.PrinterSettings = PrintDialog.PrinterSettings
    
        Dim psz As New Printing.PaperSize
    
        PrintDoc.PrinterSettings.PrinterName = printerName
    
        psz.RawKind = Printing.PaperKind.Custom
    
        Dim printSize as Size = New Size(MMInPixel(58), MMInPixel(58))
        psz.Width = printSize.Width
        psz.Height = printSize.Height
    
        '---- Set the paper size
        PrintDoc.DefaultPageSettings.PaperSize = psz
    
        PrintDoc.Print()
    
    End Sub
    
    Private Sub PrintDoc_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDoc.PrintPage
    
        Dim f As New Font("Calibri", 11, FontStyle.Regular, GraphicsUnit.Point)
    
        With e.Graphics
    
            .SmoothingMode = SmoothingMode.HighQuality
            .TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
    
            .DrawString("C", printFont, Brushes.Black, MMInPixel(0), MMInPixel(50))
    
        End With
    
    End Sub
    
    Private inchInMM As Double = 25.4          'mm = 1 inch
    Private dpi As Integer = 96
    
    Private Function MMInPixel(value As Integer) As Integer
    
        Return Math.Round((value / inchInMM) * dpi, MidpointRounding.AwayFromZero)
    
    End Function