Lachlan B's Blog

Generating barcodes with zen barcode generator

Someone asked me on Sunday if it would be possible to generate a PDF that had a barcode in it. I haven't generated a "normal" boring 2D barcode before, so I thought I'd give it a crack. I find a library named Barcode Rendering Framework, downloaded it, looked for the documentation on how to use it... and there isn't any.

I mean, there is literally none. The answer is "look at the code samples". This attitude drives me up the wall. It would seriously take the developer 10 minutes to write a good document explaining how the thing works and how to use it. But can they be bothered? Nope. So after much head scratching and stuffing around I figured it out.

private string getBarcode(int type)
{
	BarcodeSymbology s = BarcodeSymbology.Code39C;
	BarcodeDraw drawObject = BarcodeDrawFactory.GetSymbology(s);
	var metrics = drawObject.GetDefaultMetrics(60);
	metrics.Scale = 2;
	var barcodeImage = drawObject.Draw("1234123132", metrics);

	using (MemoryStream ms = new MemoryStream())
	{
	    barcodeImage.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
	    byte[] imageBytes = ms.ToArray();

	    return Convert.ToBase64String(imageBytes);
	}
}


And then to embed it on the page I just use an image tag:

 <img src="data:image/png;base64,bytearraydatagoeshere" /> 

Which produces this:



Plenty more amazing samples on my amazing barcodes page.