How to Save the Barcode in 4 Bit/Pixel Format?

First generate the barcode in the default Pixel format (Format32bppArgb):

System.Drawing.Size optimalSize = myBarcode.CalculateOptimalBitmapSize(null, 2, 2);
myBarcode.BoundingRectangle = new Rectangle(0, 0, optimalSize.Width, optimalSize.Height);
Bitmap barcodeImage = myBarcode.DrawBitmap();

Then convert it to a bitmap with the Pixel format you need:

Bitmap converted = barcodeImage.Clone (new Rectangle(0, 0, barcodeImage.Width, barcodeImage.Height), PixelFormat.Format4bppIndexed);
// MessageBox.Show(converted.PixelFormat.ToString());

How to Encode Binary Data (2D Codes)

Even if you use an escape sequence for binary data the encoder will use Codepage Conversion (example: \x88 leads to a different value in Data Matrix as desired).


  • Switch off codepage conversion (use Encoding Mode LowByte)
  • Force binary encoding mode if available (see PDF417 Encoding Mode, Data Matrix EnforceBinaryEncoding)
Relevant for DP Premium Address and other applications where you encode binary data in a 2D symbol (Data Matrix etc).

Bad Image Format Exception after Deployment of Web Application

You get a System.BadImageFormatException (an attempt was made to load a program with an incorrect format) after you have deployed your ASP. NET project to your IIS web server. During development there was no such problem.

Reason: Visual Studio is a 32 Bit application and the development server usually runs as 32 Bit process. Therefore the 32 Bit version of TECIT.TBarCode.DLL has been embedded into your project and is now part of your ./bin folder. But your IIS runs the worker thread as 64 Bit process and now loads the wrong format.

Option #1: Deploy the 64-Bit version of the Assembly

Use the version from the C:\Program Files\Common Files\TEC-IT\TBarCode\[version] folder (this is the x64 version). Exchange the ../bin/TECIT.TBarCode.dll file on your target system with that version.

Option #2: Let the GAC do the work

Remove the TECIT.TBarCode.dll completely from your bin folder. In that case the TECIT.TBarCode.dll from the global assembly cache (GAC) will be loaded. The common language runtime loads the correct version automatically because the GAC holds both versions, 32 and 64 Bit. Prerequisite: The setup of TBarCode SDK must be executed on the target server, the setup installs the DLLs in the GAC for you.

If you don't see an effect immediately, restart your application pool or perform an "iisreset" on the command line (take care, this restarts ALL and sessions will be lost).

How can I Create a Bitmap Optimized for Thermal Printers?

The following sample code in VB .NET generates a barcode image optimized for thermal printer output (resolutions such as 203 dpi).

Dim bc As New TECIT.TBarCode.Barcode()

bc.BarcodeType = TECIT.TBarCode.BarcodeType.EanUcc128
bc.Data = "1234567890123"

' set font size
bc.Font = New System.Drawing.Font("Arial", 15, System.Drawing.FontStyle.Bold, GraphicsUnit.Point)

bc.TextDistance = 1.1

bc.BearerBarType = TECIT.TBarCode.BearerBarType.TopAndBottom
bc.BearerBarWidth = 2.4

' adjust quiet zone in [Modules] (recommended for bitmaps)
bc.QuietZoneUnit = TECIT.TBarCode.QuietZoneUnit.Modules
bc.QuietZoneLeft = 12
bc.QuietZoneRight = 12

' important: set printer resolution of thermal printer
bc.Dpi = 203

' 203 dpi --> Module Width = 0.5005 = 4 Pixel per Module
Dim moduleWidth As New Single
moduleWidth = 0.5004926  'need exact value here!

bc.SizeMode = TECIT.TBarCode.SizeMode.CustomModuleWidth
bc.ModuleWidth = moduleWidth + 0.001
bc.AdjustModuleWidthToPixelRaster = True

Dim width As New Single
Dim height As New Single

' size in [mm]
width = bc.CalculateBarcodeWidth(Nothing)
height = 35

' convert size to [Pixels]
width = width / (25.4 / bc.Dpi)
height = height / (25.4 / bc.Dpi)

' adjust bitmap size
Dim drawBitmapRect As New Rectangle(0, 0, width, height)
bc.BoundingRectangle = drawBitmapRect

' output to file
bc.Draw("barcode.bmp", TECIT.TBarCode.ImageType.Bmp)

How can I Create a Readable PDF417 Bitmap with Constant Size?

The following sample code in C# ASP .NET generates a PDF417 image with constant size.

Barcode barcode = new Barcode();
barcode.Data = strMyData;
barcode.BarcodeType = BarcodeType.Pdf417;
barcode.Pdf417.EncodingMode = PdfEncodingMode.Binary;

// with dpi = 100 we get 1 Pixel = 0.254 mms
barcode.Dpi = 100;

 // we should specify the number of horizontal data columns
 // this inhibits the symbol to change its horizontal size regardless of data
 barcode.Pdf417.NumberOfColumns = 16; // use a value, which fits to your available space !!

 // now calculate optimal bitmap size for the bar code
 barcode.SizeMode = SizeMode.FitToBoundingRectangle;
 Size optimalSize = barcode.CalculateOptimalBitmapSize(null, 1, 1);

 // we already could use this optimal Size for saving the image
 // barcode.BoundingRectangle = new Rectangle(0, 0, optimalSize.Width,  optimalSize.Height);
 // barcode.Draw(filename, ImageType.Jpg);

 // but we want a constant bitmap size,
 // which fits exactly into your predefined space

 Size finalSize = new Size(350, 200); // final bitmap size in Pixel

 // so we have to add empty spaces around the symbol via adding a quiet zone
 barcode.QuietZoneUnit = QuietZoneUnit.Pixel;

 // calculate the required empty quiet zone we have to add

if (finalSize.Width > optimalSize.Width)
  barcode.QuietZoneRight = finalSize.Width - optimalSize.Width;
  // should not occur!! Reduce the Pdf417.NumberOfColumns
  finalSize.Width = optimalSize.Width;
if (finalSize.Height > optimalSize.Height)
  barcode.QuietZoneBottom = finalSize.Height - optimalSize.Height;
  // should not occur!! Increase final bitmap size
  finalSize.Height = optimalSize.Height;

barcode.BoundingRectangle = new Rectangle(0, 0, finalSize.Width, finalSize.Height);
barcode.Draw(filename, ImageType.Jpg);

How can I Optimize PDF417 Symbols in my ASP.NET Web Control?

Option #1

Add the following attributes to your TBarCode .NET Web Control. This will generate an optimized symbol, which fits into a 120 x 120 pixel matrix. Increase both the Width/Height and the NumberOfColumns attribute if required.

<cc2:BarcodeControl id="BarcodeControl1"
  Width="120" Height="120"
  Barcode-MustFit="True" ErrorHandling="ShowMessage" 

Option #2

In the Page Load event or after you have set the bar code data apply the following calculation. This code will use width/height ratio of 1:3 for the graphical modules.

Barcode barcode = BarcodeControl1.Barcode;
barcode.SizeMode = SizeMode.FitToBoundingRectangle;  
System.Drawing.Size optimalSize = barcode.CalculateOptimalBitmapSize(null, 1, 1);

BarcodeControl1.Width = new Unit(optimalSize.Width, UnitType.Pixel);
BarcodeControl1.Height = new Unit(optimalSize.Height, UnitType.Pixel);  


How Can I Create a Readable Code 39 Bitmap?

The following sample code in ASP .NET generates a Code 39 image.

//Code 39
Barcode barcode = new Barcode();
barcode.Data = "10030000007611107871900002199908";
barcode.BarcodeType = BarcodeType.Code39;

// with dpi = 100 we get 1 Pixel = 0.254 mms
barcode.Dpi = 100;

// bar code size should adapt to bounding rectangle
barcode.SizeMode = SizeMode.FitToBoundingRectangle;

// set default size of symbol (define the default height)
barcode.BoundingRectangle = new Rectangle(0, 0, 254, 100 /* = 1 inch */);
// now calculate optimal bitmap size for the bar code
Size optimalSize = barcode.CalculateOptimalBitmapSize(null, 1, 1);

// update rectangle to optimized size
barcode.BoundingRectangle  = new Rectangle(0, 0, optimalSize.Width, optimalSize.Height);
barcode.Draw(filename, ImageType.Jpg);

How Can I Create a 26x26 Data Matrix for DP Premiumadress?

The following sample code for C# .NET shows you how to adjust the settings for Data Matrix:

Barcode barcode = new TECIT.TBarCode.Barcode();
barcode.BarcodeType = BarcodeType.DataMatrix;
barcode.DataMatrix.Size = DataMatrixSize.Square26x26;
barcode.DataMatrix.Format = DataMatrixFormat.Default;
barcode.DataMatrix.ShallEnforceBinaryEncoding = true;

barcode.SizeMode = SizeMode.CustomModuleWidth;
barcode.ModuleWidth = 0.423;

barcode.EncodingMode = EncodingMode.Hexadecimal;
// set preformatted data (Bytes = Hex codes)
barcode.Data = "444541080D02540BE3FF0052232D242D000065000000010100015A313031000000000000000000000000";

Error "Catastrophic Failure" during Licensing

On specific systems (e.g. W2012R2, IIS8.5) you may encounter an error if you apply the license key immediately after creating an instance of the bar code object. This occurs because the underlying (native) TBarCode DLL has not been initialized at this point - possibly due to delayed loading of dependency DLLs or another timing issue.

As a workaround try to set any property before applying the license - see below:

TECIT.TBarCode.Barcode oBC = new TECIT.TBarCode.Barcode();
oBC.BarcodeType = TECIT.TBarCode.BarcodeType.Code128; // set a property of the object
oBC.License("Licensee", TECIT.TBarCode.LicenseType.DeveloperOrWeb, 1, "Key", TECIT.TBarCode.TBarCodeProduct.Barcode2D);

Performance: Caching Barcode Images in ASP.NET Applications

File Based Caching

The CacheDirectory property only accepts virtual paths from the web server. It is not possible to use a physical path such as c:\temp. Temporary barcode images should be created within the local (virtual) application directory (where you can find the *.aspx files) or in a subdirectory.

CacheDirectory="." or CacheDirectory="barcodefiles"

Memory Based Caching

With the following setting all barcode images will be stored in the web server's cache memory:


In order to use memory caching you must include a custom HTTP handler BarcodeHttpHandler in the <httpHandlers> section of your web.config file (you might need to create this section first, if it does not exist). It should look similar to this:

    <add verb="GET" path="BarcodeHttpHandler.axd" 
               Version=, Culture=neutral, 
               PublicKeyToken=1B5F4306B234B83D" />

Based on the example shown above, you probably need to change the version number depending on your package. Under c:\windows\assembly, look for TECIT.TBarCode to find the correct version.

If you need more detailed instructions go to:

> Start Menu > TEC-IT TBarCode 9.0 > Developer Manuals >TBarCode .NET Developer Reference (BarcodeHttpHandler Class)

Using TBarCode ASP.NET in Web Farms (IIS 7.0)

If you use TBarCode ASP.NET Web Control in a Web Farm you may encounter the following exception:

Exception Type: System.ApplicationException
Message: The requested image is no longer cached.

The TBarCode .NET Web Control uses the HttpContext.Cache object to store the generated barcode image. Since http requests are load balanced within a web farm it can occur that a specific Web Control receives a request for an image, which has been generated on a different application server (and therefore is not available in its local cache).

To overcome this problem you could

  • Synchronize the HttpContext.Cache object on all servers in the web farm (="distributed caches"). This could be done with extra programming or additional third party software.
  • or simply use Client Affinity in IIS 7.0 (recommended)

Having client affinity enabled all requests are tagged with a cookie so that subsequent requests (from the same client) are routed to the same server in the web farm.

See Application Request Routing (Step 3 – Configure client affinity)

Application Request Routing provides a client affinity feature that maps a client to a content server behind Application Request Routing for the duration of a client session. When this feature is enabled, the load balancing algorithm is applied only for the very first request from the client.