Pass the Graphics type instance, graph, into your procedure so you can paint on it. Create some objects to hold positioning. Origy and EndY will be constant over the printing, but curX is the main thing that will vary to make the barcode’s lines. We are printing or not printing every pixel, and since the pixel is the default unit of the image, this works nicely. Now we will get rid of any asterisks (*) in our code since they should not be used in the text code ever, only on the ends. We loop through the letters of the code now including the asterisks.
Code Listing 2 – Printing the Code39 Barcode
Private Sub PrintCode39(ByVal graph As Graphics)
Dim rHeight As Integer = _height - 7
Dim curPattern As String
Dim origx As Integer = 4
Dim origy As Integer = 2
Dim endY As Integer = origy + rHeight
Dim curX As Integer
curX = origx
Dim pattern As String
Dim code As String = "*" & Replace(_code, "*", "") & "*"
For i As Integer = 0 To code.Length - 1
pattern = Me.GetC39Pattern(code.Substring(i, 1))
For Each patt As Char In pattern
If patt = "1"c Then
graph.DrawLine(Pens.Black, curX, origy, curX, endY)
curX += 1
Else
curX += 1
End If
Next
Next
End Sub
We want to print the pattern associated with each letter of the code. To get the code is different for each barcode. For Code39 it is a simple matter of a select statement to get the right pattern. For UPC-A, notice that although we only print numbers so there are only nine digits to be concerned with, there are separate sets of patterns for the left six digits, versus the right six digits (UPC-A always has 12 digits in the code).
Printing the barcode pattern is a simple matter of looping through each character of the code. If the first char type in the pattern is “1”c then print, otherwise just update the curX positon object to leave a blank space in your barcode’s printed pattern. The UPC-A has fixed constant patterns at front, middle, and end called “Guard bars” to make the barcode easier to read, so those parts are constant printed patterns. Notice though that the same pattern loop is used for both barcode formats.
Image 1 – The Barcodes
Reference
I figured out how to do the UPC-A code by reading the information titled Encyclopedia: Universal Bar Code.