Skip to footer content
USING IRONBARCODE

How to Generate Barcodes in C# Using IronBarcode

IronBarcode is a .NET barcode library that lets you generate and read barcodes in C# with just a few lines of code. You can create Code 128, QR codes, EAN-13, PDF-417, Data Matrix, and dozens of other barcode types -- then export to PNG, JPEG, TIFF, BMP, PDF, or HTML. This guide walks you through installation, core generation patterns, styling, export formats, and best practices so you can add reliable barcode output to any .NET application.

How Do You Install a Barcode Generator Library Using NuGet Package Manager?

Open Visual Studio and install the NuGet package with this command in the Package Manager Console:

Install-Package BarCode

Barcode Generator C# Source Code Using IronBarcode: Image 1 - Installation

The NuGet package supports .NET 10, .NET 8, .NET 6, .NET Core, .NET Standard, and .NET Framework -- making it compatible with Windows applications and cross-platform .NET applications. IronBarcode supports deployment to Docker containers, Azure, and Linux servers. Find more details and reference documentation on the IronBarcode documentation page and the Iron Software GitHub project.

After installation, you will see the IronBarCode namespace available in your project. The library requires no additional runtime dependencies on Windows -- on Linux, you may need to install a few system libraries as documented in the IronBarcode Linux deployment guide.

How Do You Generate a Simple Barcode Image File in C#?

Create barcode images with just a few lines of code. The following example shows barcode generation that saves a PNG image file:

using IronBarCode;

// Generate a simple barcode and encode the string data
var barcode = BarcodeWriter.CreateBarcode("SKU-78432-X", BarcodeWriterEncoding.Code128);

// Save the barcode as a PNG image file
barcode.SaveAsPng("product-barcode.png");
using IronBarCode;

// Generate a simple barcode and encode the string data
var barcode = BarcodeWriter.CreateBarcode("SKU-78432-X", BarcodeWriterEncoding.Code128);

// Save the barcode as a PNG image file
barcode.SaveAsPng("product-barcode.png");
Imports IronBarCode

' Generate a simple barcode and encode the string data
Dim barcode = BarcodeWriter.CreateBarcode("SKU-78432-X", BarcodeWriterEncoding.Code128)

' Save the barcode as a PNG image file
barcode.SaveAsPng("product-barcode.png")
$vbLabelText   $csharpLabel

The BarcodeWriter.CreateBarcode() method accepts a string to encode and the barcode format from BarcodeWriterEncoding. The returned GeneratedBarcode reference provides styling methods and export options to save to PNG, JPEG, BMP, TIFF, PDF, or HTML.

Output

Barcode Generator C# Source Code Using IronBarcode: Image 2 - Barcode Output

Code128 is the workhorse barcode for logistics and inventory systems. It encodes uppercase letters, lowercase letters, numbers, and special characters in a compact linear format. This barcode type ensures proper scanning at shipping facilities and retail environments worldwide. When you use the SaveAsPng() method, IronBarcode automatically sets a default resolution suitable for on-screen display and standard printers.

For applications where you need to serve the barcode image directly from a web endpoint, you can use ToStream() instead of saving to disk. The stream can be written directly to an HttpResponse in ASP.NET Core or returned as a FileStreamResult from a controller action.

How Do You Create a QR Code and Other 2D Barcode Types?

IronBarcode supports all major barcode formats, including 2D barcode types such as QR Code and Data Matrix. Generate a QR code with similar syntax:

using IronBarCode;

// Create a QR code and encode URL data
var qrCode = BarcodeWriter.CreateBarcode(
    "https://ironsoftware.com/csharp/barcode/",
    BarcodeWriterEncoding.QRCode
);
qrCode.SaveAsPng("website-qr.png");
using IronBarCode;

// Create a QR code and encode URL data
var qrCode = BarcodeWriter.CreateBarcode(
    "https://ironsoftware.com/csharp/barcode/",
    BarcodeWriterEncoding.QRCode
);
qrCode.SaveAsPng("website-qr.png");
Imports IronBarCode

' Create a QR code and encode URL data
Dim qrCode = BarcodeWriter.CreateBarcode(
    "https://ironsoftware.com/csharp/barcode/",
    BarcodeWriterEncoding.QRCode
)
qrCode.SaveAsPng("website-qr.png")
$vbLabelText   $csharpLabel

QR code barcode types excel at storing URLs and larger data payloads. The library handles error correction automatically, ensuring the barcode remains scannable even when partially damaged. By default, IronBarcode uses error correction level M (medium), which recovers from roughly 15% data loss -- you can raise this to level H for printed barcodes that may be scratched or partially obscured.

Output

Barcode Generator C# Source Code Using IronBarcode: Image 3 - QR Code Output

For retail products requiring EAN-13 barcodes, generate barcode images like this:

using IronBarCode;

// Generate an EAN-13 barcode compatible with UPC for retail print applications
var eanBarcode = BarcodeWriter.CreateBarcode("5901234123457", BarcodeWriterEncoding.EAN13);
eanBarcode.SaveAsPng("retail-product.png");
using IronBarCode;

// Generate an EAN-13 barcode compatible with UPC for retail print applications
var eanBarcode = BarcodeWriter.CreateBarcode("5901234123457", BarcodeWriterEncoding.EAN13);
eanBarcode.SaveAsPng("retail-product.png");
Imports IronBarCode

' Generate an EAN-13 barcode compatible with UPC for retail print applications
Dim eanBarcode = BarcodeWriter.CreateBarcode("5901234123457", BarcodeWriterEncoding.EAN13)
eanBarcode.SaveAsPng("retail-product.png")
$vbLabelText   $csharpLabel

EAN-13 is the standard format for retail point-of-sale systems worldwide. The library calculates check digits automatically, so you only need to supply the first 12 digits of a valid GTIN-13 number. If the check digit you supply does not match, IronBarcode throws a descriptive exception rather than silently generating an unreadable barcode.

Output

Barcode Generator C# Source Code Using IronBarcode: Image 4 - EAN-13 Barcode Output

Beyond Code 128, QR Code, and EAN-13, the library supports Code 39, Code 93, UPC-A, UPC-E, ITF, Codabar, PDF-417, Aztec, and Data Matrix. A full list of supported formats is available on the IronBarcode barcode types reference page.

How Do You Create a Styled QR Code with Advanced Styling Options?

Professional barcode generation often requires advanced styling options to adjust colors and add annotations. The GeneratedBarcode class provides a fluent API with styling methods:

using IronBarCode;
using IronSoftware.Drawing;

// Create a styled barcode with advanced styling options
var styledBarcode = BarcodeWriter
    .CreateBarcode("INV-2025-001847", BarcodeWriterEncoding.Code128)
    .ResizeTo(400, 120)
    .SetMargins(20)
    .ChangeBarCodeColor(Color.DarkBlue)
    .AddAnnotationTextAboveBarcode("Invoice Number:")
    .AddBarcodeValueTextBelowBarcode();

// Verify to ensure proper scanning after styling
bool isReadable = styledBarcode.Verify();
Console.WriteLine($"Barcode verification: {(isReadable ? "PASS" : "FAIL")}");
styledBarcode.SaveAsPng("styled-invoice-barcode.png");
using IronBarCode;
using IronSoftware.Drawing;

// Create a styled barcode with advanced styling options
var styledBarcode = BarcodeWriter
    .CreateBarcode("INV-2025-001847", BarcodeWriterEncoding.Code128)
    .ResizeTo(400, 120)
    .SetMargins(20)
    .ChangeBarCodeColor(Color.DarkBlue)
    .AddAnnotationTextAboveBarcode("Invoice Number:")
    .AddBarcodeValueTextBelowBarcode();

// Verify to ensure proper scanning after styling
bool isReadable = styledBarcode.Verify();
Console.WriteLine($"Barcode verification: {(isReadable ? "PASS" : "FAIL")}");
styledBarcode.SaveAsPng("styled-invoice-barcode.png");
Imports IronBarCode
Imports IronSoftware.Drawing

' Create a styled barcode with advanced styling options
Dim styledBarcode = BarcodeWriter _
    .CreateBarcode("INV-2025-001847", BarcodeWriterEncoding.Code128) _
    .ResizeTo(400, 120) _
    .SetMargins(20) _
    .ChangeBarCodeColor(Color.DarkBlue) _
    .AddAnnotationTextAboveBarcode("Invoice Number:") _
    .AddBarcodeValueTextBelowBarcode()

' Verify to ensure proper scanning after styling
Dim isReadable As Boolean = styledBarcode.Verify()
Console.WriteLine($"Barcode verification: {(If(isReadable, "PASS", "FAIL"))}")
styledBarcode.SaveAsPng("styled-invoice-barcode.png")
$vbLabelText   $csharpLabel

The fluent API lets you chain styling methods to adjust colors, set margins, and add text in one statement. The Verify() method indicates whether your barcode remains machine-readable -- ensuring proper scanning in production after applying non-standard colors or resizing to small dimensions.

Changing bar color to a very light shade or a blue with low contrast against a white background can make the barcode fail to scan. Always call Verify() after any color change. If verification fails, either increase contrast or revert to black bars. The barcode styling and customization guide covers all available style methods in detail.

To generate multiple barcodes with consistent styling across an entire catalog, build a helper method that applies your standard styling chain to each GeneratedBarcode instance. This approach ensures uniform margins, font size, and color across thousands of generated images.

How Do You Export Barcodes to Different Image Formats?

Generate barcode images in multiple formats for different use cases. The library saves to PNG, JPEG, BMP, TIFF, PDF, and HTML:

using IronBarCode;

var barcode = BarcodeWriter.CreateBarcode("EXPORT-TEST", BarcodeWriterEncoding.Code128);

// Export barcode images to various formats
barcode.SaveAsPng("barcode.png");           // Web-compatible raster image
barcode.SaveAsJpeg("barcode.jpg");          // Compressed format for email attachments
barcode.SaveAsTiff("barcode.tiff");         // High-quality format for print workflows
barcode.SaveAsPdf("barcode.pdf");           // PDF document output
barcode.SaveAsHtmlFile("barcode.html");     // HTML for inline web embedding

// Get as bitmap stream for web APIs or database storage
System.IO.Stream barcodeStream = barcode.ToStream();
System.Drawing.Bitmap bitmapImage = barcode.ToBitmap();
using IronBarCode;

var barcode = BarcodeWriter.CreateBarcode("EXPORT-TEST", BarcodeWriterEncoding.Code128);

// Export barcode images to various formats
barcode.SaveAsPng("barcode.png");           // Web-compatible raster image
barcode.SaveAsJpeg("barcode.jpg");          // Compressed format for email attachments
barcode.SaveAsTiff("barcode.tiff");         // High-quality format for print workflows
barcode.SaveAsPdf("barcode.pdf");           // PDF document output
barcode.SaveAsHtmlFile("barcode.html");     // HTML for inline web embedding

// Get as bitmap stream for web APIs or database storage
System.IO.Stream barcodeStream = barcode.ToStream();
System.Drawing.Bitmap bitmapImage = barcode.ToBitmap();
Imports IronBarCode

Dim barcode = BarcodeWriter.CreateBarcode("EXPORT-TEST", BarcodeWriterEncoding.Code128)

' Export barcode images to various formats
barcode.SaveAsPng("barcode.png")           ' Web-compatible raster image
barcode.SaveAsJpeg("barcode.jpg")          ' Compressed format for email attachments
barcode.SaveAsTiff("barcode.tiff")         ' High-quality format for print workflows
barcode.SaveAsPdf("barcode.pdf")           ' PDF document output
barcode.SaveAsHtmlFile("barcode.html")     ' HTML for inline web embedding

' Get as bitmap stream for web APIs or database storage
Dim barcodeStream As System.IO.Stream = barcode.ToStream()
Dim bitmapImage As System.Drawing.Bitmap = barcode.ToBitmap()
$vbLabelText   $csharpLabel

The ToStream() method returns barcode data compatible with ASP.NET Core web APIs and Blazor applications. The ToBitmap() method provides a System.Drawing.Bitmap reference for further image manipulation. For stamping barcodes onto existing PDF documents, see the IronBarcode PDF barcode tutorial.

Output

Barcode Generator C# Source Code Using IronBarcode: Image 5 - PNG Barcode Output

Barcode Generator C# Source Code Using IronBarcode: Image 6 - HTML Barcode Output

Choosing the right format depends on your downstream workflow. PNG is lossless and a good default for web and application UIs. TIFF is preferred for print-production pipelines where color accuracy matters. PDF output is useful when you need a ready-to-print document that a print shop can handle directly. HTML output generates a self-contained file with an embedded base64 image -- convenient for email templates and web portals.

What Cross-Platform .NET Environments Does IronBarcode Support?

IronBarcode supports barcode generation across all major .NET platforms. Deploy to:

IronBarcode Deployment Platform Support
Platform Supported Runtimes Typical Use Cases
Windows .NET 10, .NET 8, .NET Framework 4.6.2+ Desktop apps, Windows Services, IIS web servers
Linux .NET 10, .NET 8, .NET Core 3.1+ Docker containers, AWS Lambda, Azure Functions
macOS .NET 10, .NET 8 Development environments, macOS server apps
Mobile .NET MAUI, Xamarin iOS and Android mobile applications
Cloud Azure, AWS, Google Cloud Serverless functions, containerized microservices

The IronBarcode Docker setup guide provides details on the required system libraries for containerized deployments. When running on Linux, you typically need libgdiplus and libc6-dev installed in your Docker image. On Alpine Linux, a slightly different set of packages is required -- the guide covers both Ubuntu/Debian and Alpine Dockerfiles.

For AWS Lambda deployments, the AWS Lambda deployment walkthrough explains how to bundle native dependencies in the deployment package and configure memory limits to handle barcode rendering workloads.

How Do You Follow Best Practices for Barcode Generation in .NET?

Following a consistent set of practices when generating barcode images in C# applications makes the difference between barcodes that scan reliably in the field and those that fail at the point of sale or warehouse floor. The guidelines below apply regardless of which barcode format you choose.

Choose the right barcode format for your use case. Select a format that matches your scanning environment and data requirements. Use QR codes for URLs and data payloads over 80 characters. Use Code 128 for inventory and logistics where alphanumeric data must fit in a compact linear symbol. Use EAN-13 or UPC-A for retail products that need to be registered in the GS1 system. IronBarcode's barcode format comparison page provides a side-by-side reference of all supported types, their capacity limits, and recommended use cases.

Always include sufficient quiet zones. The white space around a barcode -- called the quiet zone -- is as important as the bars themselves. Scanners use it to detect where the symbol begins and ends. Use the SetMargins() method to add at least 10 pixels of padding on every side for digital display, and at least 2.5 mm for print output. Cutting into the quiet zone is one of the most common causes of scan failures in production.

Verify after any styling change. After adjusting colors, applying gradients, or resizing to a non-standard dimension, call Verify() on the GeneratedBarcode object. If it returns false, your barcode will not scan reliably with standard hardware. Either increase the contrast or reduce the complexity of the styling change.

Use batch generation patterns for high-volume output. If your application generates thousands of barcodes -- for example, product labels or shipping manifests -- process them in a loop and reuse the same styling configuration. Avoid loading font assets or configuration objects inside the loop, as this creates unnecessary overhead. The IronBarcode batch barcode generation example demonstrates an efficient loop pattern with consistent output.

Test across multiple scanner models and lighting conditions. Barcode scanners vary in their tolerance for low-contrast colors, small module sizes, and print quality. Test printed barcodes with at least two different scanner types before deploying. For QR codes displayed on screens, test with mobile phone cameras in both bright and dim lighting. The GS1 barcode verification standards page provides authoritative guidance on symbol quality grading for retail barcodes.

Respect data capacity limits. Every barcode format has a maximum data capacity. Code 128 can encode up to approximately 48 characters comfortably before the symbol becomes too wide to print at standard label sizes. QR code capacity depends on the error correction level -- at level H, the maximum is around 1,273 alphanumeric characters. Exceeding capacity forces the library to either throw an exception or silently degrade quality. Check the QR code data capacity reference on Wikipedia for a quick capacity table.

Follow .NET dispose patterns. The GeneratedBarcode and any streams returned by ToStream() implement IDisposable. Wrap them in using statements to release unmanaged resources promptly, especially in high-throughput web applications where barcode generation happens per request.

Understanding common failure modes also helps you build more resilient generation code. The three most frequent causes of scan failures are: insufficient quiet zone, bar color too close to background color, and barcode scaled below the minimum module size for the chosen format. IronBarcode's Verify() method catches all three at runtime.

For reading barcodes back from generated images -- for round-trip testing or scanning uploaded files -- see the IronBarcode barcode reader guide. The reader API mirrors the writer API in simplicity and supports the same broad range of formats.

The ISO/IEC 15417 standard for Code 128 and the ISO/IEC 18004 standard for QR codes define the technical specifications that IronBarcode conforms to. Reviewing the relevant standard for your target barcode type helps you understand the constraints the library must work within.

What Are Your Next Steps?

This guide covered generating barcode images in C# using IronBarcode -- from NuGet installation through Code 128, QR code, and EAN-13 generation, advanced styling with the fluent API, multi-format export, cross-platform deployment, and production best practices.

To go further, explore these resources:

Download IronBarcode to add barcode functionality to your .NET applications, or start a free 30-day trial to generate barcode images in your environment without a license key.

Frequently Asked Questions

How do you install IronBarcode using NuGet Package Manager?

Open Visual Studio, navigate to Tools > NuGet Package Manager > Package Manager Console, and run: Install-Package BarCode. Alternatively, search for 'IronBarcode' in the NuGet Package Manager UI and click Install.

What types of barcodes can you generate using IronBarcode?

IronBarcode supports generating a wide range of barcode types including QR codes, Code 128, Code 39, Code 93, UPC-A, UPC-E, EAN-13, EAN-8, PDF-417, Data Matrix, Aztec, and more.

Can IronBarcode generate barcodes in different image formats?

Yes, IronBarcode can generate barcodes in PNG, JPEG, BMP, TIFF, PDF, and HTML formats using the SaveAsPng, SaveAsJpeg, SaveAsTiff, SaveAsPdf, and SaveAsHtmlFile methods.

Is IronBarcode compatible with .NET 10?

Yes, IronBarcode is fully compatible with .NET 10, .NET 8, .NET 6, .NET Core, .NET Standard, and .NET Framework, allowing you to integrate barcode generation into cross-platform applications.

How do you customize the appearance of a barcode using IronBarcode?

IronBarcode provides a fluent API on the GeneratedBarcode class. Chain methods like ResizeTo(), SetMargins(), ChangeBarCodeColor(), AddAnnotationTextAboveBarcode(), and AddBarcodeValueTextBelowBarcode() to customize appearance. Always call Verify() after styling to confirm the barcode remains scannable.

Does IronBarcode support barcode reading and scanning?

Yes, IronBarcode supports reading and scanning barcodes from images, PDFs, and streams using the BarcodeReader class and its Read methods.

Can you generate barcodes in bulk using IronBarcode?

Yes, IronBarcode supports bulk generation. Iterate through your data in a loop, call BarcodeWriter.CreateBarcode() for each item, and apply your standard styling chain. Reuse configuration objects outside the loop for efficiency.

Is there a trial version of IronBarcode available?

Yes, IronBarcode offers a free 30-day trial license. Visit ironsoftware.com/csharp/barcode/licensing/#trial-license to get a trial key and use all features without a watermark during evaluation.

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