Print Barcode Labels with vb.net

Good afternoon everyone! I had an extremely quiet evening last night and this morning. We are really at crunch time at work right now but I think I am where I need to be with what I need to do.

Anyway, today’s topic is one that can throw a lot of for fits. We need to print barcode labels but some characters don’t translate as you would expect in print. So this class is a little old but it still works. Make it a great day!

 

Imports System.Drawing.Printing
Imports System.Drawing.Graphics
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents BarcodeDoc As barcode.TextPrint ‘BarcodingParts.TextPrint

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        ‘This call is required by the Windows Form Designer.
        InitializeComponent()

        ‘Add any initialization after the InitializeComponent() call

    End Sub

    ‘Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    ‘Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    ‘NOTE: The following procedure is required by the Windows Form Designer
    ‘It can be modified using the Windows Form Designer. 
    ‘Do not modify it using the code editor.
    Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument
        Me.Button1 = New System.Windows.Forms.Button
        Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
        Me.SuspendLayout()
        ‘
        ‘Button1
        ‘
        Me.Button1.Location = New System.Drawing.Point(196, 224)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        ‘
        ‘PrintPreviewDialog1
        ‘
        Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
        Me.PrintPreviewDialog1.Enabled = True
        Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
        Me.PrintPreviewDialog1.Location = New System.Drawing.Point(132, 132)
        Me.PrintPreviewDialog1.MinimumSize = New System.Drawing.Size(375, 250)
        Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
        Me.PrintPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty
        Me.PrintPreviewDialog1.Visible = False
        ‘
        ‘Form1
        ‘
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        ‘ BarcodeDoc = New BarcodingParts.TextPrint("*00417955*", "Here is Second line from Extended Barcode")
        ‘ BarcodeDoc.Font = New Font("FREE 3 OF 9 Extended", 30) ‘<—- Free Font on the internet or add your own
        ‘ OR USE THIS
        BarcodeDoc = New TextPrint("*00417 955*", "Here is Second line from Regular Barcode")
        BarcodeDoc.Font = New Font("FREE 3 OF 9", 30) ‘<—- Free Font on the internet or add your own
        ‘For Pre-veiw Printing
        PrintPreviewDialog1.Document = BarcodeDoc
        PrintPreviewDialog1.ShowDialog()

        ‘For Direct Printing
        Dim PrintDialog1 As New PrintDialog
        ‘PrintDialog1.Document = BarcodeDoc
        ‘PrintDocument1.Print()
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        BarcodeDoc.PrinterSettings.PrinterName = InitializeDefaultPrinter() ‘"Zebra"
        BarcodeDoc.DefaultPageSettings.Margins.Left = 10
        BarcodeDoc.DefaultPageSettings.Margins.Right = 10
        BarcodeDoc.DefaultPageSettings.Margins.Top = 40
    End Sub
#Region " Initialize Default Printer "
    Public Function InitializeDefaultPrinter()
        ‘ Set the specified printer to the default printer for this program. Return
        ‘ true if the printer was found.

        Dim objprinter As PageSettings = New PageSettings
        Dim strname = objprinter.PrinterSettings.PrinterName

        InitializeDefaultPrinter = strname
    End Function
#End Region
End Class

‘CLASS FILE

Public Class TextPrint
    ‘ Inherits all the functionality of a PrintDocument
    Inherits Printing.PrintDocument
    ‘ Private variables to hold default font and text
    Private fntPrintFont As Font
    Private strText As String
    Private strText2 As String
    Private PrintBarCodeText As String
    Public Sub New(ByVal Text As String, ByVal Text2 As String)
        ‘ Sets the file stream
        MyBase.New()
        strText = Text
        strText2 = Text2
    End Sub
    Public Property Text() As String
        Get
            Return strText
        End Get
        Set(ByVal Value As String)
            strText = Value
        End Set
    End Property
    Public Property Text2() As String
        Get
            Return Trim(strText2)
        End Get
        Set(ByVal Value As String)
            strText2 = Trim(Value)
        End Set
    End Property
    Public Property CodeText() As String
        Get
            PrintBarCodeText = Trim(Replace(strText, "*", " "))
            Return PrintBarCodeText
        End Get
        Set(ByVal Value As String)
            If PrintBarCodeText = "" Then
                PrintBarCodeText = Trim(Replace(Value, "*", " "))
            End If
            PrintBarCodeText = Value
        End Set
    End Property
    Protected Overrides Sub OnBeginPrint(ByVal ev As Printing.PrintEventArgs)
        ‘ Run base code
        MyBase.OnBeginPrint(ev)
        ‘ Sets the default font
        If fntPrintFont Is Nothing Then
            fntPrintFont = New Font("Times New Roman", 12)
        End If
    End Sub
    Public Property Font() As Font
        ‘ Allows the user to override the default font
        Get
            Return fntPrintFont
        End Get
        Set(ByVal Value As Font)
            fntPrintFont = Value
        End Set
    End Property
    Protected Overrides Sub OnPrintPage(ByVal ev As Printing.PrintPageEventArgs)
        ‘ Provides the print logic for our document

        ‘ Run base code
        MyBase.OnPrintPage(ev)
        ‘ Variables
        Static intCurrentChar As Integer
        Dim intPrintAreaHeight, intPrintAreaWidth, intMarginLeft, intMarginTop As Integer
        ‘ Set printing area boundaries and margin coordinates
        With MyBase.DefaultPageSettings
            intPrintAreaHeight = .PaperSize.Height – .Margins.Top – .Margins.Bottom
            intPrintAreaWidth = .PaperSize.Width – .Margins.Left – .Margins.Right
            intMarginLeft = .Margins.Left ‘X
            intMarginTop = .Margins.Top   ‘Y
        End With
        ‘ If Landscape set, swap printing height/width
        If MyBase.DefaultPageSettings.Landscape Then
            Dim intTemp As Integer
            intTemp = intPrintAreaHeight
            intPrintAreaHeight = intPrintAreaWidth
            intPrintAreaWidth = intTemp
        End If
        ‘ Calculate total number of lines
        Dim intLineCount As Int32 = CInt(intPrintAreaHeight / Font.Height)
        ‘ Initialise rectangle printing area
        Dim rectPrintingArea As New RectangleF(intMarginLeft, intMarginTop, intPrintAreaWidth, intPrintAreaHeight)
        ‘ Initialise StringFormat class, for text layout
        Dim objSF As New StringFormat(StringFormatFlags.LineLimit)
        ‘ Figure out how many lines will fit into rectangle
        Dim intLinesFilled, intCharsFitted As Int32
        Dim stringSize As New SizeF
        stringSize = ev.Graphics.MeasureString(Mid(strText, _
                    UpgradeZeros(intCurrentChar)), Font, New SizeF(intPrintAreaWidth, _
                    intPrintAreaHeight), objSF, intCharsFitted, intLinesFilled)
        ‘ Print the text to the page
        ev.Graphics.DrawString(Mid(strText, _
            UpgradeZeros(intCurrentChar)), Font, Brushes.Black, rectPrintingArea, objSF)

        ‘ Initialise rectangle printing area for the Barcode Text
        Dim stringFont As New Font("Arial", 12, FontStyle.Bold)
        Dim size As SizeF = ev.Graphics.MeasureString(CodeText, stringFont)
        Dim size2 As SizeF = ev.Graphics.MeasureString(strText2, stringFont)
        Dim BCPrintingArea As New RectangleF(stringSize.Width – size.Width / 2, intMarginTop + stringSize.Height, intPrintAreaWidth, intPrintAreaHeight)

        ‘Move Second line to center
        Dim moveStr As Integer
        moveStr = stringSize.Width – size2.Width / 2
        moveStr = intMarginLeft + (moveStr / intMarginLeft)
        Dim BCPrintingArea2 As New RectangleF(moveStr, intMarginTop + stringSize.Height + size2.Height, intPrintAreaWidth, intPrintAreaHeight)

        ‘ADD text Bottom of Barcode
        ev.Graphics.DrawString(CodeText, stringFont, Brushes.Black, BCPrintingArea)
        ev.Graphics.DrawString(strText2, stringFont, Brushes.Black, BCPrintingArea2)

        ‘ Increase current char count
        intCurrentChar += intCharsFitted
        ‘ Check whether we need to print more
        If intCurrentChar < strText.Length Then
            ev.HasMorePages = True
        Else
            ev.HasMorePages = False
            intCurrentChar = 0
        End If
    End Sub
    Public Function UpgradeZeros(ByVal Input As Integer) As Integer
        ‘ Upgrades all zeros to ones
        ‘ – used as opposed to defunct IIF or messy If statements
        If Input = 0 Then
            Return 1
        Else
            Return Input
        End If
    End Function

End Class

Technorati Tags: ,,,,,,,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,

Advertisements
  1. #1 by Emerald on May 4, 2009 - 3:52 am

    hi.. what should I do if I wanna print the barcode from Textboxes like the following format?. eg.||||||| |||||||| |||||||| ||||||123456ABCDEFG HIJLMNOPTextbox data come from Database columns. And then, will print the above format without using the PrintDocument or PrintDialogue controls. Thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: