Stat Tracker

Friday, January 14, 2011

Generating a Barcode in a Visualforce Page using Javascript

You can generate a barcode in a Visualforce Page using Javascript pretty easily. Some folks forget that you can execute Javascript in a Visualforce page. This opens you up to a lot of the goodies you can do with the client browser.

The trick is to find the right Javascript library which provides the type of barcode you want to generate, or you could always write your own.

At a highlevel, the steps you need to do are:

1. Upload a JS Library (someJSLib.js) to your Static Resources in Salesforce.
2. Reference the JS Library in your Visualforce page by using the <apex:includeScript> tag.
3. Execute the Javascript functions to generate the barcode content and display in your page.

For this example, I am using a Barcode 39 Javascript library provided by

1. First I upload the JS Library to my Static Resources:

2. After I have uploaded the library, I embed the JS file in my VF Page using the <apex:includeScript> tag:
<apex:includeScript value="{!$Resource.BarcodeScript}"/>

3. I execute javascript in the Visualforce page to generate the barcode (Full VF Page Code):
<apex:page standardController="Position__c">
    <apex:includeScript value="{!$Resource.BarcodeScript}"/>
    <apex:detail relatedList="false"></apex:detail>
    <div id="inputdata">{!Position__c.Name}</div>
    <div id="externalbox" style="width:5in"></div>
    <script type="text/javascript">
    /* <![CDATA[ */
      function get_object(id) {
       var object = null;
       if (document.layers) {
        object = document.layers[id];
       } else if (document.all) {
        object = document.all[id];
       } else if (document.getElementById) {
        object = document.getElementById(id);
       return object;
     /* ]]> */

4. When I view this page it will take the Name field from my Position__c object and encode it in the Barcode:

That's all it takes!

The only challenging part really is finding JS Libraries that are opensource and support your barcode format.

Here are some websites that have JS Libraries available:

Barcode 39:
Barcode 39: