Wednesday, March 22, 2017

Barcode Salesforce and PDF

Barcode Salesforce and PDF


Hi All,
Recently I faced one issue where i need to generate Barcode on the fly in VF and also render that as PDF. I searched on Net and community, found some people have done Barcode generation using Javascript. But in my case i need to render it as PDF and VF does not support Javascript when renderAs PDF. So i decided to go the way to generate Barcode image. The first thing came in my mind is PHP/GD way to generate Barcode image and use that url in VF to show image. Then i found this site useful and very useful PHP script which fits my need
http://www.sid6581.net/cs/php-scripts/barcode/

I used this script, done some modification in this and hosted on my site And used in my VF page as below:-

<apex:image value="http://www.aslambari.com/barcode.php?barcode=CS1001&width=200&text=1&height=100" />


Here is some details about how you use the url and parameters to generate barcode:
URL: http://www.aslambari.com/barcode.php
Params:
barcode: [any text to render as barcode]
text: [0 or 1]
format: [jpeg/png/gif]
width: [the width you want]
height: [the height you want]



It works great if my VF render as normal HTML page, but as soon as i make it renderAs="PDF", VF again not works, it does not allow dynamic generated images. So again i got disappointed.
Then i thought again and did apex code to fetch the dynamic binary data generated my PHP site url and save it into attachment and use that url in my VF page. I was thinking this time i will win for sure, but again it did not work. HttpResponse does not allow Blob response, it always gives response as String and that mingled my image data. Disappointed again.

Then finally i have decided to create dynamic generated barcode on PHP and save as temprary images and use that url in my img tag and renderAs="PDF", this time i got success :)

Here is the working demo for my work:-
https://labsprojects-developer-edition.ap1.force.com/BarCodeSample

If you need complete code for above demo site, here is the link:
http://www.aslambari.com/SF_Barcode.zip

Enjoy barcoding :)

Thanks
Aslam Bari

Available link for download