IRONSOFTWAREHOME
USING IRONBARCODE

Generate Barcodes in ASP.NET Core Web Apps

Curtis Chau
Curtis Chau
Updated: February 27, 2026

Integrating barcode generation into an ASP.NET web application opens powerful capabilities for inventory management, product tracking, and document automation. This tutorial demonstrates how to generate barcodes in a .NET Core project using IronBarcode -- a barcode library that supports over 30 formats including QR Code, Data Matrix, Code 128, and UPC A.

The following quick example shows how to create a Code 128 barcode and return it as a PNG image from an MVC controller action:

using IronBarCode;
using Microsoft.AspNetCore.Mvc;

public IActionResult GenerateBarcode(string data)
{
    GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(data, BarcodeWriterEncoding.Code128);
    barcode.ResizeTo(400, 120);
    barcode.AddBarcodeValueTextBelowBarcode();
    byte[] barcodeBytes = barcode.ToPngBinaryData();
    return File(barcodeBytes, "image/png");
}

Start your free trial to follow along with the complete tutorial code examples below.

How Do You Install a Barcode Library in a .NET Core Project?

Adding barcode generation capabilities to an ASP.NET Core web application requires installing the IronBarcode NuGet package. Open Visual Studio and use the Package Manager Console to install the dependencies:

PM > Install-Package BarCode

The package is compatible with .NET Core 6, 7, 8, 10, and newer versions, as well as .NET Framework 4.6.2+. The library handles all dependencies automatically, requiring no additional barcode fonts or system configuration. Once installed, add the namespace reference to the controller or service file:

using IronBarCode;

What .NET Versions and Platforms Are Supported?

IronBarcode targets all modern .NET runtimes:

  • .NET 10, 9, 8, 7, 6 -- fully supported LTS and STS releases
  • .NET Framework 4.6.2+ -- legacy application support
  • Deployment targets -- Windows, Linux, macOS, Docker, Azure, AWS
  • Mobile targets -- Android and iOS via .NET MAUI

No external GD libraries, native codecs, or barcode font installations are required. The library is entirely self-contained and resolves all encoding logic internally.

How Do You Add the Namespace to a Controller?

After installing the NuGet package, reference the IronBarCode namespace at the top of any controller, service, or Razor Page model where barcode generation is needed:

using IronBarCode;
using Microsoft.AspNetCore.Mvc;

This single using directive gives access to BarcodeWriter, QRCodeWriter, BarcodeReader, and all supporting types for both generation and reading barcodes.

How Do You Generate Barcodes in an ASP.NET Core Web Application?

Creating barcodes in an MVC controller involves the BarcodeWriter class from IronBarcode. The following example demonstrates a complete controller action that creates a Code 128 barcode based on URL or text provided by a user:

using IronBarCode;
using Microsoft.AspNetCore.Mvc;

public class BarcodeController : Controller
{
    public IActionResult GenerateBarcode(string data)
    {
        // Generate barcode from input data
        GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(
            data,
            BarcodeWriterEncoding.Code128);
        barcode.ResizeTo(400, 120);
        barcode.AddBarcodeValueTextBelowBarcode();
        // Return as image for display in browser
        byte[] barcodeBytes = barcode.ToPngBinaryData();
        return File(barcodeBytes, "image/png");
    }
}

Output Barcode Image

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Image 1 - Generated Barcode

The BarcodeWriter.CreateBarcode() method accepts barcode data as the first parameter and the encoding format as the second. This approach creates barcodes dynamically based on user input or database values.

For saving barcode images to a project folder, use the SaveAsImage() method:

barcode.SaveAsImage("wwwroot/images/generated-barcode.png");

The library supports multiple output formats including PNG, GIF, BMP, SVG, and JPEG. You can also export barcodes as HTML for embedding directly into web pages.

How Do You Return a Barcode as a File Download?

To return the barcode as a downloadable file rather than an inline image, set the Content-Disposition header in the response:

public IActionResult DownloadBarcode(string data)
{
    GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(data, BarcodeWriterEncoding.Code128);
    barcode.ResizeTo(400, 120);
    byte[] pdfBytes = barcode.ToPdfBinaryData();
    return File(pdfBytes, "application/pdf", "barcode.pdf");
}

This pattern is useful for shipping label generation, product labeling workflows, and any scenario where the end user needs to save or print a barcode document directly.

What Barcode Types Are Supported for Web Applications?

IronBarcode supports over 30 formats. Here are the details on how to create the most commonly used types:

QR Code Generation

// Create QR Code with custom size
GeneratedBarcode qrCode = QRCodeWriter.CreateQrCode(
    "https://example.com/product/12345",
    500,
    QRCodeWriter.QrErrorCorrectionLevel.Medium);
qrCode.SaveAsPng("product-qr.png");

Output QR Code

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Figure 2

QR Code generation supports error correction levels that determine how much of the code can be damaged while remaining readable. Use Medium or High for print QR code applications where physical wear is expected. Learn more about QR Code customization options.

Data Matrix and Other 2D Formats

// Create Data Matrix barcode
GeneratedBarcode dataMatrix = BarcodeWriter.CreateBarcode(
    "DMX-2024-001",
    BarcodeWriterEncoding.DataMatrix);
dataMatrix.SaveAsGif("datamatrix.gif");

Output Data Matrix

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Image 3 - Generated Data Matrix

Data Matrix barcodes excel in scenarios requiring compact, high-density encoding. The library also generates PDF417, Aztec, and MaxiCode formats. These 2D barcode types store significantly more data than linear formats while maintaining reliable scan accuracy.

Linear Barcodes (UPC, EAN, Code 39)

// Create UPC-A barcode for retail products
GeneratedBarcode upcBarcode = BarcodeWriter.CreateBarcode(
    "012345678905",
    BarcodeWriterEncoding.UPCA);
upcBarcode.SaveAsPng("upc-barcode.png");

Output

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Image 4 - Generated barcode

UPC A and EAN barcodes include automatic checksum validation, preventing encoding errors in the barcode generation process. For a full list of supported formats see the barcode format reference.

How Do You Customize and Style Barcode Images?

Styling barcodes for a web application involves adjusting colors, fonts, margins, and annotations. The fluent API makes customization straightforward:

GeneratedBarcode styledBarcode = BarcodeWriter.CreateBarcode(
    "STYLED-2024",
    BarcodeWriterEncoding.Code128);
// Apply styling
styledBarcode.ResizeTo(450, 150);
styledBarcode.SetMargins(20);
styledBarcode.ChangeBarCodeColor(IronSoftware.Drawing.Color.DarkBlue);
styledBarcode.AddAnnotationTextAboveBarcode("Product ID:");
styledBarcode.AddBarcodeValueTextBelowBarcode();
// Export to multiple formats
styledBarcode.SaveAsPng("styled-barcode.png");
styledBarcode.SaveAsPdf("styled-barcode.pdf");

Styled Barcode Image

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Image 5 - Output styled barcode

The SetMargins() method adds white space around the barcode for better scanner readability. You can adjust font settings for annotation text, change the font family and font size, and customize barcode styling extensively. The library renders text using system fonts without requiring external barcode fonts.

How Do You Embed a Barcode Directly in a Razor View?

For ASP.NET MVC views, generate barcodes as Base64 strings for direct HTML embedding without saving files to disk:

public IActionResult DisplayBarcode()
{
    GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(
        "INV-2024-0042",
        BarcodeWriterEncoding.Code128);
    string base64Image = barcode.ToDataUrl();
    ViewBag.BarcodeImage = base64Image;
    return View();
}

Displayed Barcode

ASP .NET Barcode Generation: Build a Barcode Generator for Your Web Application: Image 6 - Barcode displayed in our browser

In the Razor view, display it within a <div> element:

<div class="barcode-container">
    <img src="@ViewBag.BarcodeImage" alt="Generated Barcode" />
</div>
<div class="print-actions">
    <button onclick="window.print()">Print Barcode</button>
</div>
HTML

This approach eliminates the need to save barcode images to the file system, keeping the web service stateless. The complete API reference documents all available methods and properties.

How Do You Read and Scan Barcodes in ASP.NET Core?

Reading barcodes from uploaded images or file streams is handled by the BarcodeReader class. This is useful in receiving workflows, returns processing, and any scenario where a scanned barcode needs to be decoded server-side:

using IronBarCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

public class BarcodeScanController : Controller
{
    public IActionResult ScanBarcode(IFormFile uploadedImage)
    {
        using var stream = uploadedImage.OpenReadStream();
        var results = BarcodeReader.Read(stream);
        if (results.Count > 0)
        {
            string decodedValue = results[0].Value;
            return Ok(new { barcode = decodedValue });
        }
        return BadRequest("No barcode detected in image.");
    }
}

The BarcodeReader.Read() method accepts file paths, streams, and System.Drawing.Bitmap objects. It automatically detects the barcode format and returns a collection of BarcodeResult objects, each containing the decoded value, format type, and position in the image. When multiple barcodes appear in a single image -- for example, on a warehouse shelf photograph -- the reader returns all detected values in the collection, not just the first one.

Performance is also worth considering for high-throughput ASP.NET applications. The reader supports region-of-interest scanning, which crops the image to a specific pixel rectangle before analysis. This significantly reduces processing time when barcodes always appear in a known area of the image.

For advanced scenarios such as adjusting contrast for low-quality images or tuning detection sensitivity, refer to the barcode reading documentation.

How Do You Export Barcodes to PDF in ASP.NET?

Generating barcodes embedded directly in PDF documents is a common requirement for shipping labels, warehouse tags, and compliance documents. IronBarcode supports saving directly to PDF format:

GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(
    "SHIP-2024-99471",
    BarcodeWriterEncoding.Code128);
barcode.ResizeTo(500, 150);
barcode.AddAnnotationTextAboveBarcode("Shipping Label");
barcode.AddBarcodeValueTextBelowBarcode();
barcode.SaveAsPdf("shipping-label.pdf");

For multi-barcode PDF documents -- for example, a page of product labels -- generate each barcode separately and combine them using a PDF library. The IronPDF integration guide explains how to stamp barcodes onto existing PDF templates, which is useful for adding barcodes to pre-designed label layouts.

The SaveAsPdf() method also accepts output dimensions so the rendered PDF page matches the physical label size required by label printers.

How Do You Handle Barcode Generation Errors and Validation?

Barcode encoding rules vary by format. For example, UPC-A requires exactly 11 or 12 digits, EAN-13 requires exactly 12 or 13, and Code 128 has a 48-character practical limit for readable output at standard sizes. Passing invalid data raises an IronBarCodeEncoderException.

Handle encoding errors explicitly in controller actions:

public IActionResult SafeGenerate(string data, string format)
{
    try
    {
        var encoding = Enum.Parse<BarcodeWriterEncoding>(format, true);
        GeneratedBarcode barcode = BarcodeWriter.CreateBarcode(data, encoding);
        return File(barcode.ToPngBinaryData(), "image/png");
    }
    catch (IronBarCodeEncoderException ex)
    {
        return BadRequest($"Encoding error: {ex.Message}");
    }
    catch (ArgumentException ex)
    {
        return BadRequest($"Unknown format: {ex.Message}");
    }
}

For production use, validate input data length and character set before calling CreateBarcode(). The IronBarcode documentation provides format-specific encoding constraints for each supported barcode type.

What Are Your Next Steps?

Building an ASP.NET barcode generator with IronBarcode provides a reliable solution for creating, styling, and exporting barcode images in .NET Core web applications. The library handles complex encoding standards automatically while offering extensive customization through a developer-friendly API. Whether generating QR codes for mobile scanning, Data Matrix barcodes for industrial applications, or UPC codes for retail, IronBarcode integrates directly with ASP.NET MVC controllers and Razor pages.

Explore these resources to go further:

You can test the complete feature set during the free evaluation period. For production deployment and commercial use, view licensing options to select the appropriate license for your project requirements. The library supports bitmap and vector exports, with each version maintaining compatibility across Windows, Linux, Android, and iOS deployment targets.

For questions, benchmarks against alternative barcode libraries for .NET, or enterprise integration support, visit the IronBarcode support portal.

First Step:
arrow pointer
Curtis Chau
Technical Writer

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.

...
Read More

Related Articles

Key in blue circle

Get your free 30-day Trial Key instantly.

Your trial license will be sent to your email address

No limitations. 100% unlocked. No credit card.

bullet_checkedNo credit card or account creation requiredNo limitations. 100% unlocked. No credit card.
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
Book your free Live Demo
Booking Badge

Trusted by Millions of Engineers Worldwide

Iron Software's customer logos
Get Your No-Obligation Consult
Complete the form below or email sales@ironsoftware.com
Your details will always be kept confidential.
Trusted by Millions of Engineers Worldwide
Iron Software's customer logos
Get your free 30-day Trial Key instantly.
No credit card or account creation required