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 code page conversion (example: \x88 leads to a different value in Data Matrix as desired).


  • Switch off code page 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 a 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 Swiss QR Code V2?

The following sample code in C# .NET shows how to create the data format for Swiss QR Code 2.0.

public enum CurrencyCodes

public enum ReferenceTypes

private const string fldSep = "\n";

decimal? Amount = new decimal(99.01);
CurrencyCodes Currency = CurrencyCodes.CHF;
ReferenceTypes ReferenceType = ReferenceTypes.SCOR;

string QRIBAN            = "";
string CreditorIBAN      = "CH180024024037606600Q";
string CreditorName      = "Robert Schneider AG";
string CreditorAddress1  = "Rue du Lac 1268";
string CreditorAddress2  = "2501 Biel";
string CreditorCountry   = "CH";

string DebtorName        = "Max Mustermann";
string DebtorAddress1    = "Musterstrasse 2";
string DebtorAddress2    = "1234 Musterstadt";
string DebtorCountry     = "CH";
string QRReference       = "";
string CreditorReference = "RF18539007547034";
string Message           = "Optional";
string BillInfo          = "";
string Parameter1        = "";
string Parameter2        = "";

/// returns the Data string valid for Swiss QR-Code version 2
public string GetDataString()
  var sb = new StringBuilder();

  sb.Append("SPC" + fldSep);
  sb.Append("0200" + fldSep);
  sb.Append("1" + fldSep);

  if (ReferenceType == ReferenceTypes.QRR)
    sb.Append(QRIBAN + fldSep);
    sb.Append(CreditorIBAN + fldSep);

  sb.Append("K" + fldSep);
  sb.Append(CreditorName + fldSep);
  sb.Append(CreditorAddress1 + fldSep);
  sb.Append(CreditorAddress2 + fldSep);
  sb.Append(fldSep + fldSep);
  sb.Append(CreditorCountry + fldSep);

  //ultimate creditor
  sb.Append(fldSep + fldSep + fldSep + fldSep + fldSep + fldSep + fldSep);

  if (Amount.HasValue)
    sb.Append(Amount.Value.ToString("#########.00", System.Globalization.CultureInfo.InvariantCulture) + fldSep);

  sb.Append(Currency + fldSep);

  if (DebtorName + DebtorAddress1 + DebtorAddress2 + DebtorCountry == string.Empty)
    sb.Append(fldSep + fldSep + fldSep + fldSep + fldSep + fldSep + fldSep);
    sb.Append("K" + fldSep);
    sb.Append(DebtorName + fldSep);
    sb.Append(DebtorAddress1 + fldSep);
    sb.Append(DebtorAddress2 + fldSep);
    sb.Append(fldSep + fldSep);
    sb.Append(DebtorCountry + fldSep);

  sb.Append(ReferenceType + fldSep);
  if (ReferenceType == ReferenceTypes.QRR)
    sb.Append(QRReference + fldSep);
  else if (ReferenceType == ReferenceTypes.SCOR)
    sb.Append(CreditorReference + fldSep);

  sb.Append(Message + fldSep);
  sb.Append("EPD" + fldSep);
  sb.Append(BillInfo + fldSep);
  sb.Append(Parameter1 + fldSep);

  return sb.ToString(); // NOTE: does not end with fieldSeparator

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";

How Can I Create a Data Matrix with 1BPP and 1200 DPI?

The following sample code for C# .NET shows you how to create a TIFF with 1 bpp (B/W) and 1200 dpi.

Barcode barcode = new TECIT.TBarCode.Barcode();
barcode.BarcodeType = BarcodeType.DataMatrix;
barcode.Dpi = -1;  // Use DPI from screen DC
barcode.SizeMode = SizeMode.FitToBoundingRectangle;
barcode.Data = "TEST 1234";

float dpi = 1200;
int nScale = 12; // 1 Dot = 12 Pixel  (at 1200 dpi, this is 0.254 mm)
// Calculate bounding rectangle using a scaled module width adapted to Pixel boundaries
Size sizePx = barcode.CalculateOptimalBitmapSize(null, nScale, nScale);
barcode.BoundingRectangleF = new RectangleF(0, 0, sizePx.Width, sizePx.Height);

Bitmap myBarcode = barcode.DrawBitmap();
//myBarcode.SetResolution(dpi, dpi);
//myBarcode.Save("c:\\temp\\ExportedFile.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Bitmap converted = myBarcode.Clone(new Rectangle(0, 0, myBarcode.Width, myBarcode.Height), System.Drawing.Imaging.PixelFormat.Format1bppIndexed);
converted.SetResolution(dpi, dpi);
converted.Save("c:\\temp\\ExportedFile.tif", System.Drawing.Imaging.ImageFormat.Tiff);

How Can I Create a 2D Mailmark Type 7?

The following sample code for VB .NET shows you how to adjust the settings for 2D Mailmark Type 7 bitmap file:

' 2D Mailmark Type 7 - 24x24 matrix size
' Module size 0.508 mm (300 dpi), total size 12.2 x 12.2 mm

Dim myBarcode As New TECIT.TBarCode.Barcode
myBarcode.BarcodeType = TECIT.TBarCode.BarcodeType.Mailmark_2D
myBarcode.DataMatrix.Size = TECIT.TBarCode.DataMatrixSize.Square24x24

myBarcode.SizeMode = TECIT.TBarCode.SizeMode.CustomModuleWidth
myBarcode.ModuleWidth = 0.508F
myBarcode.Dpi = 300

myBarcode.Data = "JGB 012100123412345678AB19XY1A 0             123456"

' retrieve final size in [mm]
Dim finalSizeMM As SizeF
finalSizeMM = myBarcode.CalculateBarcodeSize(Nothing) ' will return [mm]

Dim widthPx As Integer
Dim heightPx As Integer

' convert to Pixel
widthPx = finalSizeMM.Width * myBarcode.Dpi / 25.4
heightPx = finalSizeMM.Height * myBarcode.Dpi / 25.4

' adjust bitmap size and save as BMP
myBarcode.BoundingRectangleF = New RectangleF(0, 0, widthPx, heightPx)
myBarcode.Draw("C:\temp\2DMailmark.bmp", TECIT.TBarCode.ImageType.Bmp)

Why I See a Different Font in EPS and AI Export?

TBarCode SDK does not embed the fonts into EPS and AI. It just references the font by specifying the font name. So it depends on the output device or graphics suite if the font is available and how the font is rendered.

For EPS only font names which are standard in PostScript or font names, which do not contain any blanks/spaces in the referenced font name are allowed.

Helvetica is a standard PostScript font but it may not be included in Illustrator (Helvetica Font missing in Illustrator).

EPS: In order to avoid problems on printers, which do not have Arial installed, we convert references to Arial always to Helvetica, which looks similar and is a standard PS font (available in all printers). If this is not desired, you have an option, which controls if there is a font replacement applied or not. This is the UseDeviceFonts option.

Here is sample code for EAN13 SC2 – 100%:

Export to EPS with Standard Postscript Fonts (Arial ⇒ Helvetica)

Barcode barcode = new Barcode();
barcode.BarcodeType = BarcodeType.Ean13;

barcode.BoundingRectangleF = new RectangleF(0, 0, 37.29F, 25.91F); // SC2 size
barcode.SizeMode = SizeMode.CustomModuleWidth;
barcode.ModuleWidth = 0.330F; // SC2 module width

barcode.Data = "123456789012";
barcode.Font = new Font("Arial", 9);
barcode.UseDeviceFonts = true;

barcode.Draw("c:\\temp\\TestFile.eps", ImageType.Eps);
barcode.Draw("c:\\temp\\", ImageType.Ai);

If you open the exported EPS file with a text editor, you see Helvetica instead of Arial:

/Helvetica findfont
9.0000 scalefont setfont

This is how it looks if you open the EPS file with a PostScript viewer (like GSView):

EPS Barcode Export

If you open the exported AI file with a text editor, you see:

%%IncludeResource: font ArialMT
%AI3_BeginEncoding: _ArialMT ArialMT
[/_ArialMT/ArialMT 0 0 1 TZ
For AI export we use ArialMT as standard font (if Arial has been adjusted).

Export to EPS and Keep the Adjusted Font (Arial ⇒ Arial)

The printer or the graphics software must support “Arial”! Font names must not contain blanks/spaces!

Barcode barcode = new Barcode();
barcode.BarcodeType = BarcodeType.Ean13;

barcode.BoundingRectangleF = new RectangleF(0, 0, 37.29F, 25.91F);
barcode.SizeMode = SizeMode.CustomModuleWidth;
barcode.ModuleWidth = 0.330F;

barcode.Data = "123456789012";
barcode.Font = new Font("Arial", 9);
barcode.UseDeviceFonts = false;

barcode.Draw("c:\\temp\\TestFile.eps", ImageType.Eps);
barcode.Draw("c:\\temp\\", ImageType.Ai);

If you open the exported EPS file with a text editor, you see:

/Arial findfont
9.0000 scalefont setfont

If you open the exported AI file with a text editor you see:

%%IncludeResource: font Arial
%AI3_BeginEncoding: _Arial Arial
[/_Arial/Arial 0 0 1 TZ


In order to use the adjusted font for the export, you can set UseDeviceFonts = false. It depends also what you want to do with the EPS file. If you want to send the file just “as is” to a printer or printing system, it is maybe better to use Helvetica with UseDeviceFonts = true. We recommend to try printing first before you make a decision about DeviceFonts.

PDF Export without HRT

For PDF export, there is no font rendering included in the TBarCode SDK - that is why you don’t get any font or text output if you chose PDF export format.

If you need PDF export with font embedding, you may use our TFORMer Label Printing SDK. The TFORMer SDK supports the same barcodes as the TBarCode SDK. Or - you can also use Barcode Studio in command line mode – you call BCStudio.exe from your own program code and pass the barcode data and file name to BCStudio (for the available command line parameters see the BCStudio user manual). Alternatively - if you want to use PDF libraries from third party vendors, you may use the Callback drawing mechanism of TBarCode SDK – here you get the coordinates of the bars and of the text and with these coordinates you implement the barcode with the drawing and font / text rendering functions of the PDF library. Samples for how to use the Callback drawing are included in the SDK.

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.