Monday, December 2, 2013

Generate barcode and attach it to a record in Salesforce

So today I came across a requirement where in I had to generate a bar code at run time and then attach it to the record.  For generating the bar code I used the jquery library and it was pretty straight forward.
The jquery library used
 <script type="text/javascript" src="jquery-1.3.2.min.js"></script>   
 <script type="text/javascript" src="jquery-barcode.js"></script> 
Now to take that bar code out as an image and attach it with the record had a lot of challenges.  Here is the solution for it.

1. Use HTML5 and ensure that the Barcode is generated as a canvas output. Here is code for the same.
<canvas id="canvasTarget" width="300" height="50"></canvas>  
 $("#canvasTarget").barcode("123456789", "code128",{barWidth:2, barHeight:30,output:"canvas"});

2. Use the toDataURL function to extract the base64 string encoded data for the barcode rendered in the canvas.
 var oCanvas = document.getElementById("canvasTarget"); 
  imageblob= oCanvas.toDataURL(); 



3. Now when you get this data it is prefixed with a lot of information like its an image , its type etc. Now before we post this data in salesforce and use it to generate an attachment, we need to clean it. You can either clean it before posting the data or clean it at the server side. I decided to clean it before posting hence I used the split function.

var res = imageblob.split(",")

4. Next is the actual posting. For this you can either you user javascript remoting or simple form post. As my form has no other elements hence I decided to post the entire form. I created a hidden element on my form and set the value of that element with the cleaned base 64 data.

5. Finally I wrote an action function which would post the form and assign it to my string variable in controller which is my case is "docbody"

6. In the controller the string element which contains the encoded data would be converted into a blob object using the base54decode method.
 Attachment a = new Attachment();
 a.ParentId = recid;
 a.Name = 'Test.jpeg';
 a.Body = EncodingUtil.base64Decode(docbody);
  insert a;

And finally I could generate a dynamic barcode and attach it to a record.

No comments:

Post a Comment