Skip to footer content
USING IRONBARCODE

Data Matrix Generator in C# -- Complete Tutorial with Code Examples

Data Matrix barcodes pack a significant amount of encoded data into a small physical area, making them the preferred choice for labeling pharmaceuticals, marking electronic components, and tracking items in inventory management systems where space is limited. This tutorial walks you through how to generate Data Matrix barcodes in C# using IronBarcode, customize their appearance, encode different data types, and export them into various file formats -- all with straightforward, production-ready code.

Get stated with IronBarcode now.
green arrow pointer

What Makes Data Matrix Barcodes Special?

Data Matrix barcodes are 2D symbols that encode data in a grid of black and white dots arranged into rows and columns. Unlike traditional linear barcodes such as UPC or EAN, they can store up to 2,335 alphanumeric characters or 3,116 numerical digits in a space as small as 10 x 10 modules. Their built-in Reed-Solomon error correction allows them to be accurately read by modern barcode scanners even when up to 30% of the symbol is damaged.

These characteristics make Data Matrix ideal for marking small parts, postal barcodes, and electronic components, as well as labeling in healthcare and logistics centers. The healthcare industry relies on GS1 Data Matrix standards for medication tracking, while manufacturers embed them in production lines to identify items worldwide. Because a single barcode can hold so much data, they are now used internationally across industries seeking complete application traceability.

The ISO/IEC 16022 standard governs Data Matrix encoding, defining the ECC200 variant that IronBarcode uses by default. ECC200 provides the most efficient error correction and the greatest data capacity of any Data Matrix version, making it the right choice for new implementations.

Data Matrix vs. Common Barcode Formats
Format Type Max Characters Error Correction Typical Use Case
Data Matrix (ECC200) 2D 2,335 alphanumeric Reed-Solomon (~30%) Pharma, electronics, logistics
QR Code 2D 4,296 alphanumeric Reed-Solomon (up to 30%) URLs, marketing, payments
UPC-A 1D 12 digits None Retail product identification
Code 128 1D ~50 characters Checksum only Shipping, general logistics

How Do You Install the Barcode Library in a C# Project?

Installing IronBarcode takes under a minute using the NuGet Package Manager. Open the Package Manager Console in Visual Studio and run:

Install-Package BarCode

Data Matrix Generator in C#: Complete Guide with IronBarcode: Image 1 - Image 1 of 5 related to Data Matrix Generator in C#: Complete Guide with IronBarcode

Alternatively, search for BarCode by Iron Software in the NuGet Package Manager GUI. After installation, add the namespace to your C# file:

using IronBarCode;
using IronBarCode;
Imports IronBarCode
$vbLabelText   $csharpLabel

That is all the setup required. IronBarcode handles all the complex Data Matrix encoding internally, following the ISO/IEC 16022 standard, so you can focus on application logic. For additional setup options such as offline installation or custom package sources, see the IronBarcode installation guide and the advanced NuGet installation page.

Supported Target Frameworks

IronBarcode targets .NET 10, .NET 8, .NET 6, .NET 5, .NET Standard 2.0, and .NET Framework 4.6.2 and above. If your project targets any of these frameworks, the NuGet package installs without additional configuration.

How Do You Create Your First Data Matrix Barcode?

Generating a Data Matrix barcode requires just one line of code:

// Create a Data Matrix barcode with product information
var myBarcode = BarcodeWriter.CreateBarcode("PROD-12345-2024", BarcodeWriterEncoding.DataMatrix);

// Save as a high-quality PNG image
myBarcode.SaveAsImage("product-label.png");
// Create a Data Matrix barcode with product information
var myBarcode = BarcodeWriter.CreateBarcode("PROD-12345-2024", BarcodeWriterEncoding.DataMatrix);

// Save as a high-quality PNG image
myBarcode.SaveAsImage("product-label.png");
' Create a Data Matrix barcode with product information
Dim myBarcode = BarcodeWriter.CreateBarcode("PROD-12345-2024", BarcodeWriterEncoding.DataMatrix)

' Save as a high-quality PNG image
myBarcode.SaveAsImage("product-label.png")
$vbLabelText   $csharpLabel

This code creates a Data Matrix barcode encoding the text PROD-12345-2024 and saves it as a PNG file. The BarcodeWriterEncoding.DataMatrix parameter tells IronBarcode to use the Data Matrix format. The resulting barcode automatically applies the ECC200 specification, which includes built-in error correction and ensures reliable scanning across real-world conditions.

Barcode Output

Data Matrix Generator in C#: Complete Guide with IronBarcode: Image 2 - First barcode output

For immediate use in applications, retrieve the barcode as a bitmap or export it directly to a PDF:

// Get barcode as a bitmap for direct display in a UI control
var barcodeBitmap = myBarcode.ToBitmap();

// Save as PDF for document integration
myBarcode.SaveAsPdf("barcode-document.pdf");
// Get barcode as a bitmap for direct display in a UI control
var barcodeBitmap = myBarcode.ToBitmap();

// Save as PDF for document integration
myBarcode.SaveAsPdf("barcode-document.pdf");
' Get barcode as a bitmap for direct display in a UI control
Dim barcodeBitmap = myBarcode.ToBitmap()

' Save as PDF for document integration
myBarcode.SaveAsPdf("barcode-document.pdf")
$vbLabelText   $csharpLabel

IronBarcode supports exporting to PNG, JPEG, BMP, GIF, TIFF, SVG, and PDF formats. You can also create and stamp barcodes onto existing PDF documents to embed them inside purchase orders, invoices, or shipping manifests.

What Data Types Can You Encode in a Data Matrix Barcode?

Data Matrix supports several encoding modes, each optimized for a different character set. IronBarcode automatically selects the most efficient mode based on the content you supply:

// Encode alphanumeric product codes
var productCode = BarcodeWriter.CreateBarcode("ABC-123-XYZ", BarcodeWriterEncoding.DataMatrix);
productCode.SaveAsImage("product-code.png");

// Encode numeric serial numbers (numeric mode uses less space)
var serialNumber = BarcodeWriter.CreateBarcode("987654321098765", BarcodeWriterEncoding.DataMatrix);
serialNumber.SaveAsImage("serial-number.png");

// Encode URLs for product landing pages or support portals
var urlCode = BarcodeWriter.CreateBarcode("https://example.com/product/12345", BarcodeWriterEncoding.DataMatrix);
urlCode.SaveAsImage("url-datamatrix.png");

// Encode Unicode text for international applications
var unicodeBarcode = BarcodeWriter.CreateBarcode("製品-2024-東京", BarcodeWriterEncoding.DataMatrix);
unicodeBarcode.SaveAsImage("unicode-datamatrix.png");
// Encode alphanumeric product codes
var productCode = BarcodeWriter.CreateBarcode("ABC-123-XYZ", BarcodeWriterEncoding.DataMatrix);
productCode.SaveAsImage("product-code.png");

// Encode numeric serial numbers (numeric mode uses less space)
var serialNumber = BarcodeWriter.CreateBarcode("987654321098765", BarcodeWriterEncoding.DataMatrix);
serialNumber.SaveAsImage("serial-number.png");

// Encode URLs for product landing pages or support portals
var urlCode = BarcodeWriter.CreateBarcode("https://example.com/product/12345", BarcodeWriterEncoding.DataMatrix);
urlCode.SaveAsImage("url-datamatrix.png");

// Encode Unicode text for international applications
var unicodeBarcode = BarcodeWriter.CreateBarcode("製品-2024-東京", BarcodeWriterEncoding.DataMatrix);
unicodeBarcode.SaveAsImage("unicode-datamatrix.png");
Imports System

' Encode alphanumeric product codes
Dim productCode = BarcodeWriter.CreateBarcode("ABC-123-XYZ", BarcodeWriterEncoding.DataMatrix)
productCode.SaveAsImage("product-code.png")

' Encode numeric serial numbers (numeric mode uses less space)
Dim serialNumber = BarcodeWriter.CreateBarcode("987654321098765", BarcodeWriterEncoding.DataMatrix)
serialNumber.SaveAsImage("serial-number.png")

' Encode URLs for product landing pages or support portals
Dim urlCode = BarcodeWriter.CreateBarcode("https://example.com/product/12345", BarcodeWriterEncoding.DataMatrix)
urlCode.SaveAsImage("url-datamatrix.png")

' Encode Unicode text for international applications
Dim unicodeBarcode = BarcodeWriter.CreateBarcode("製品-2024-東京", BarcodeWriterEncoding.DataMatrix)
unicodeBarcode.SaveAsImage("unicode-datamatrix.png")
$vbLabelText   $csharpLabel

Numeric data uses a compact encoding mode that reduces barcode size compared to alphanumeric text. Binary encoding handles special characters and Unicode text without manual configuration. IronBarcode selects the most efficient encoding mode automatically, so you do not need to specify it explicitly.

Output

Here, all four data types have successfully been encoded into valid Data Matrix barcodes.

Data Matrix Generator in C#: Complete Guide with IronBarcode: Image 3 - Data Matrix barcodes created with 4 different data types

For a deeper look at encoding options and character set support, see the IronBarcode encoding documentation and the barcode data type reference.

How Do You Customize the Appearance of a Data Matrix Barcode?

IronBarcode exposes a full set of barcode customization options for controlling size, color, annotations, and margins:

// Create barcode with custom styling
var customBarcode = BarcodeWriter.CreateBarcode("CUSTOM-2024", BarcodeWriterEncoding.DataMatrix);

// Set specific dimensions in pixels
customBarcode.ResizeTo(500, 500);

// Adjust colors for special label requirements
customBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkBlue);
customBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.LightGray);

// Add human-readable text below the barcode symbol
customBarcode.AddAnnotationTextBelowBarcode("Product: CUSTOM-2024");

// Set margins to preserve the required quiet zone
customBarcode.SetMargins(10);

customBarcode.SaveAsImage("custom-datamatrix.png");
// Create barcode with custom styling
var customBarcode = BarcodeWriter.CreateBarcode("CUSTOM-2024", BarcodeWriterEncoding.DataMatrix);

// Set specific dimensions in pixels
customBarcode.ResizeTo(500, 500);

// Adjust colors for special label requirements
customBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkBlue);
customBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.LightGray);

// Add human-readable text below the barcode symbol
customBarcode.AddAnnotationTextBelowBarcode("Product: CUSTOM-2024");

// Set margins to preserve the required quiet zone
customBarcode.SetMargins(10);

customBarcode.SaveAsImage("custom-datamatrix.png");
' Create barcode with custom styling
Dim customBarcode = BarcodeWriter.CreateBarcode("CUSTOM-2024", BarcodeWriterEncoding.DataMatrix)

' Set specific dimensions in pixels
customBarcode.ResizeTo(500, 500)

' Adjust colors for special label requirements
customBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkBlue)
customBarcode.ChangeBackgroundColor(IronSoftware.Drawing.Color.LightGray)

' Add human-readable text below the barcode symbol
customBarcode.AddAnnotationTextBelowBarcode("Product: CUSTOM-2024")

' Set margins to preserve the required quiet zone
customBarcode.SetMargins(10)

customBarcode.SaveAsImage("custom-datamatrix.png")
$vbLabelText   $csharpLabel

These customizations help match corporate branding requirements or specific labeling standards. The ResizeTo method maintains proper module proportions, which is essential for Data Matrix readability at any scanner distance. Color changes accommodate special printing processes or substrate constraints such as colored labels or metallic materials. The quiet zone margin set by SetMargins meets the minimum whitespace requirement defined in the ISO/IEC 16022 specification.

Data Matrix Generator in C#: Complete Guide with IronBarcode: Image 4 - Custom data matrix output

Choosing the Right Barcode Size

The minimum readable size for a Data Matrix barcode depends on the scanner and printing resolution. For general-purpose scanning, a module size of at least 0.3 mm is recommended. At 300 DPI print resolution, a 500-pixel barcode measures approximately 42 mm square -- sufficient for reliable handheld scanning. For smaller labels, increase the DPI or reduce the data payload to keep the symbol within a scannable size range.

How Do You Generate Multiple Barcodes in a Batch?

Batch generation reduces the work involved in creating large sets of Data Matrix codes for production runs, shipping labels, or serialized inventory:

// Generate barcodes for a batch of products
string[] productIds = { "PROD-001", "PROD-002", "PROD-003", "PROD-004", "PROD-005" };

foreach (string id in productIds)
{
    var batchBarcode = BarcodeWriter.CreateBarcode(id, BarcodeWriterEncoding.DataMatrix);
    batchBarcode.ResizeTo(150, 150);
    batchBarcode.AddAnnotationTextBelowBarcode(id);

    // Save each barcode with a unique filename
    string filename = $"barcode_{id.Replace("-", "_")}.png";
    batchBarcode.SaveAsImage(filename);
}
// Generate barcodes for a batch of products
string[] productIds = { "PROD-001", "PROD-002", "PROD-003", "PROD-004", "PROD-005" };

foreach (string id in productIds)
{
    var batchBarcode = BarcodeWriter.CreateBarcode(id, BarcodeWriterEncoding.DataMatrix);
    batchBarcode.ResizeTo(150, 150);
    batchBarcode.AddAnnotationTextBelowBarcode(id);

    // Save each barcode with a unique filename
    string filename = $"barcode_{id.Replace("-", "_")}.png";
    batchBarcode.SaveAsImage(filename);
}
' Generate barcodes for a batch of products
Dim productIds As String() = {"PROD-001", "PROD-002", "PROD-003", "PROD-004", "PROD-005"}

For Each id As String In productIds
    Dim batchBarcode = BarcodeWriter.CreateBarcode(id, BarcodeWriterEncoding.DataMatrix)
    batchBarcode.ResizeTo(150, 150)
    batchBarcode.AddAnnotationTextBelowBarcode(id)

    ' Save each barcode with a unique filename
    Dim filename As String = $"barcode_{id.Replace("-", "_")}.png"
    batchBarcode.SaveAsImage(filename)
Next
$vbLabelText   $csharpLabel

This pattern suits logistics and healthcare workflows that require large label sets, each associated with a unique identifier. For web applications, stamping barcodes directly onto PDF documents or streaming them as byte arrays enables real-time label generation without saving intermediate files.

Data Matrix Generator in C#: Complete Guide with IronBarcode: Image 5 - Batch data matrix barcode creation

Async and Multi-Thread Processing for Large Batches

When generating thousands of barcodes, synchronous processing becomes a bottleneck. IronBarcode provides async and multi-thread processing capabilities that allow you to generate barcodes in parallel across multiple CPU cores. For a batch of 10,000 labels, parallel processing can reduce total generation time by an order of magnitude compared to sequential loops.

For high-throughput scenarios, consider grouping barcodes into PDF sheets using IronBarcode's PDF stamping API rather than saving thousands of individual image files, which can create filesystem overhead on both Windows and Linux deployments.

How Do You Read and Verify Data Matrix Barcodes?

Generating barcodes is only half the workflow -- verifying that scanners can correctly read them closes the quality loop. IronBarcode includes a built-in barcode reader that lets you decode a generated image immediately after creating it:

// Generate a barcode
var generated = BarcodeWriter.CreateBarcode("VERIFY-2024", BarcodeWriterEncoding.DataMatrix);
generated.SaveAsImage("verify-test.png");

// Read it back to confirm correct encoding
var results = BarcodeReader.Read("verify-test.png");
foreach (var result in results)
{
    Console.WriteLine($"Decoded value: {result.Value}");
    Console.WriteLine($"Format: {result.BarcodeType}");
}
// Generate a barcode
var generated = BarcodeWriter.CreateBarcode("VERIFY-2024", BarcodeWriterEncoding.DataMatrix);
generated.SaveAsImage("verify-test.png");

// Read it back to confirm correct encoding
var results = BarcodeReader.Read("verify-test.png");
foreach (var result in results)
{
    Console.WriteLine($"Decoded value: {result.Value}");
    Console.WriteLine($"Format: {result.BarcodeType}");
}
Imports System
Imports ZXing

' Generate a barcode
Dim generated = BarcodeWriter.CreateBarcode("VERIFY-2024", BarcodeWriterEncoding.DataMatrix)
generated.SaveAsImage("verify-test.png")

' Read it back to confirm correct encoding
Dim results = BarcodeReader.Read("verify-test.png")
For Each result In results
    Console.WriteLine($"Decoded value: {result.Value}")
    Console.WriteLine($"Format: {result.BarcodeType}")
Next
$vbLabelText   $csharpLabel

This round-trip verification pattern is particularly valuable in regulated industries such as pharmaceuticals, where the DSCSA regulation mandates that serialized barcodes on prescription drug packages are both machine-readable and correctly formatted. Running a read-back check as part of the generation pipeline catches encoding errors before labels reach the production line.

For more advanced reading scenarios, see the IronBarcode reading documentation and the barcode reading from PDF guide.

Common Scanning Compatibility Considerations

Different scanner firmware versions interpret Data Matrix symbols with varying tolerance for quiet zones and module contrast. When targeting legacy handheld scanners, increase the module size, use high-contrast black-on-white colors, and keep the quiet zone at least two modules wide. The GS1 Application Identifier guide provides encoding patterns for supply chain identifiers such as batch numbers, expiration dates, and GTINs within a single Data Matrix symbol.

What Are Your Next Steps?

Data Matrix barcode generation in C# with IronBarcode follows a consistent pattern: install the NuGet package, call BarcodeWriter.CreateBarcode with BarcodeWriterEncoding.DataMatrix, apply any required customizations, and export to your target format. The same API handles everything from single-barcode prototypes to high-volume batch pipelines.

Here are the recommended paths for taking this further:

  • Explore barcode reading: The IronBarcode reading guide covers decoding barcodes from images, PDFs, and live camera streams.
  • Try other 2D formats: IronBarcode also generates QR codes, PDF417, Aztec, and all major 1D formats using the same API.
  • Embed barcodes in documents: The PDF stamping tutorial shows how to add barcodes to existing PDFs programmatically.
  • Scale with async processing: Review the async and multi-thread guide to parallelize large batch jobs.
  • Review licensing: The IronBarcode licensing page lists options from developer to OEM redistribution.

Start a free trial to test all features without restrictions, or review the full IronBarcode documentation for detailed API references and additional code examples.

NuGet Install with NuGet

PM >  Install-Package BarCode

Check out IronBarcode on NuGet for quick installation. With over 10 million downloads, it’s transforming PDF development with C#. You can also download the DLL.

Frequently Asked Questions

What is a Data Matrix barcode?

A Data Matrix barcode is a 2D symbol governed by the ISO/IEC 16022 standard that encodes up to 2,335 alphanumeric characters or 3,116 digits in a small grid. It is commonly used in pharmaceutical labeling, electronics marking, and inventory management.

How do you generate a Data Matrix barcode in C#?

Call BarcodeWriter.CreateBarcode with your data string and BarcodeWriterEncoding.DataMatrix, then call SaveAsImage or SaveAsPdf on the result. IronBarcode handles ECC200 encoding and error correction automatically.

What are the benefits of using IronBarcode for Data Matrix generation?

IronBarcode generates ECC200 Data Matrix barcodes in one line of code, handles automatic encoding mode selection, and exports to PNG, PDF, SVG, and other formats without additional dependencies.

Can IronBarcode export Data Matrix barcodes to different file formats?

Yes. IronBarcode exports Data Matrix barcodes to PNG, JPEG, BMP, GIF, TIFF, SVG, and PDF. You can also stamp barcodes directly onto existing PDF documents.

Is it possible to customize Data Matrix barcodes with IronBarcode?

Yes. IronBarcode provides ResizeTo for dimensions, ChangeBarCodeColor and ChangeBackgroundColor for color, AddAnnotationTextBelowBarcode for human-readable text, and SetMargins for quiet zone control.

For what industries are Data Matrix barcodes particularly suitable?

Data Matrix barcodes are widely used in pharmaceuticals for DSCSA compliance, electronics for component identification, logistics for package tracking, and healthcare for GS1-compliant medication labeling.

What version of Data Matrix does IronBarcode generate?

IronBarcode generates ECC200 Data Matrix barcodes by default. ECC200 is the current ISO/IEC 16022 standard version, providing the highest data capacity and Reed-Solomon error correction.

Why use Data Matrix barcodes over other 2D codes?

Data Matrix barcodes are favored for their high data density in small physical footprints, Reed-Solomon error correction that survives up to 30% symbol damage, and ISO/IEC standardization recognized in regulated industries worldwide.

Jordi Bardia
Software Engineer
Jordi is most proficient in Python, C# and C++, when he isn’t leveraging his skills at Iron Software; he’s game programming. Sharing responsibilities for product testing, product development and research, Jordi adds immense value to continual product improvement. The varied experience keeps him challenged and engaged, and he ...
Read More

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me