I needed to add a Code 3 of 9 barcode to a ASP.NET page. Possible solutions are to use a True Type barcode font, a dynamic image created by PHP script, or a jQuery plugin. The font had issues printing from Chrome. I didn’t want to use PHP on this ASP.NET project nor did I want to add jQuery and a plugin. Since I needed a simple 5 numeric digit barcode, I dynamically rendered it client-side.
I referenced the above mentioned PHP code for some basic logic and used the CSS method for displaying the barcode from the jQuery plugin. Reading this Wikipedia page also helped. Each Code 3 of 9 character is made up of bars separated by spaces; 2 thick bars, 3 thin bars, 1 thick space and 3 thin spaces. Each character is separated with a thin space. Finally the barcode begins and ends with a sentinel “*”.
The Code
The pattern of the bars and spaces thicknesses are stored in an array to lookup. I only included patterns for numbers. After we loop through the data to create a pattern for the entire barcode, we loop through the pattern to generate the html. Bars and spaces are rendered using the left border of a div.
window.onload = function () { var code_string = document.getElementById("lblItemNum").innerHTML; var code_array = { 0: "111331311", 1: "311311113", 2: "113311113", 3: "313311111", 4: "111331113", 5: "311331111", 6: "113331111", 7: "111311313", 8: "311311311", 9: "113311311" }; var sentinel = "131131311"; var html = ""; var code = sentinel + "1"; for (k = 0; k < code_string.length; k++) { code += code_array[code_string[k]] + "1"; } code += sentinel; for (i = 1; i <= code.length; i++) { html += "<div style='border-left:" + code[i - 1] * 4 + "px solid " + ((i % 2 == 0) ? "#FFF" : "#000") + ";'></div>"; } var bar = document.getElementById("barcode"); bar.innerHTML = html; }
Some needed CSS.
#barcode div { float:left; font-size:0px; width:0; height:200px; }
The div container that centers the barcode on the page. Note width of 444px. This is calculated by summing each bar and space width. In this example, the thin is 4px and thick 12px. Each character has 6 thin and 3 thick. There are 7 characters separated by 6 thin spaces. That gives us 7 * (4px*6 + 12px*3) + 6*4px = 444px.
<div style="float: left;position: relative;margin-left: 50%;"> <div id="barcode" style="float: left;position: relative;margin-left: -50%;width:444px;"></div> </div>