How to Create Barcodes as HTML in C#

How to Export Barcodes as HTML in C#

IronBarcode enables C# developers to export generated barcodes as HTML in three formats: Data URL for inline embedding, HTML tag for direct injection, or complete HTML file for standalone use—providing versatile integration options without external dependencies.

Quickstart: Export a Barcode as an HTML Tag with One Line

Generate a barcode and export it directly as a fully-formed HTML image tag using a single fluent line of code. Get started fast without managing external image files or asset dependencies.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronBarcode with NuGet Package Manager

    PM > Install-Package BarCode

  2. Copy and run this code snippet.

    var htmlTag = BarcodeWriter.CreateBarcode("1234567890", BarcodeWriterEncoding.Code128).ToHtmlTag();
  3. Deploy to test on your live environment

    Start using IronBarcode in your project today with a free trial
    arrow pointer

How Do I Export a Barcode as a Data URL?

Before exporting a barcode as a Data URL, understand what a Data URL is. A Data URL (also known as Data URI) is a Uniform Resource Identifier that embeds data directly in the URL string. This allows inline display in web pages as if the data were external resources. Data URLs support any format: text, images, audio, video, and binary data. Use the obtained Data URL in HTML inside an image tag as a src attribute. Here's how to convert a GeneratedBarcode into a Data URL:

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsDataUrl.cs
using IronBarCode;
using System;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.QRCode);
var dataUrl = myBarcode.ToDataUrl();
Console.WriteLine(dataUrl);
$vbLabelText   $csharpLabel

Create a barcode using the CreateBarcode() method from the BarcodeWriter class with the barcode value and encoding as arguments. Get the Data URL by attaching the ToDataUrl() method to the GeneratedBarcode. This approach works with all supported barcode formats in IronBarcode.

Why Does Using Data URL Matter for Web Applications?

Data URLs provide significant advantages for web applications by reducing HTTP requests and improving page load performance. When you embed a barcode as a Data URL, the image data becomes part of the HTML document itself, eliminating separate image file requests. This benefits:

  • Single-page applications (SPAs) requiring minimal server round-trips
  • Email templates where external images might be blocked
  • Offline-capable applications functioning without network connectivity
  • Dynamic barcode generation where creating physical files is inefficient

For production deployment, see our guides on deploying to Azure or AWS deployment for cloud-based barcode generation.

When Should I Use Data URL Instead of Image Files?

Use Data URLs when barcodes are small (under 32KB) and require immediate inline rendering. Choose traditional image files stored on servers or CDNs when:

// Example: Choosing between Data URL and file export based on size
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("LARGE-DATA-STRING-HERE", BarcodeEncoding.PDF417);

// Check estimated size before choosing export method
if (barcode.BinaryStream.Length < 32768) // 32KB threshold
{
    // Use Data URL for smaller barcodes
    string dataUrl = barcode.ToDataUrl();
    // Embed directly in HTML
}
else
{
    // Save as file for larger barcodes
    barcode.SaveAsImage("large-barcode.png");
    // Reference as external resource
}
// Example: Choosing between Data URL and file export based on size
GeneratedBarcode barcode = BarcodeWriter.CreateBarcode("LARGE-DATA-STRING-HERE", BarcodeEncoding.PDF417);

// Check estimated size before choosing export method
if (barcode.BinaryStream.Length < 32768) // 32KB threshold
{
    // Use Data URL for smaller barcodes
    string dataUrl = barcode.ToDataUrl();
    // Embed directly in HTML
}
else
{
    // Save as file for larger barcodes
    barcode.SaveAsImage("large-barcode.png");
    // Reference as external resource
}
$vbLabelText   $csharpLabel

What Are the Size Limitations of Data URLs?

While modern browsers technically support Data URLs of several megabytes, practical limitations exist:

  • Internet Explorer 8: Limited to 32KB
  • Modern browsers: Support 2-4MB, but performance degrades
  • Mobile browsers: Stricter limits due to memory constraints
  • Email clients: Restrict Data URLs to 8-64KB

Keep Data URL barcodes under 32KB for optimal performance. For larger barcodes or multiple barcode generation, use our export as stream functionality for efficient memory management.

How Do I Export a Barcode as an HTML Tag?

Export a GeneratedBarcode to HTML using the ToHtmlTag() method. This method renders the GeneratedBarcode object as a fully formed HTML tag for direct injection into HTML without JavaScript, CSS, or image dependencies. The following code demonstrates HTML tag export:

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsHtmlTag.cs
using IronBarCode;
using System;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.QRCode);
var htmlTag = myBarcode.ToHtmlTag();
Console.WriteLine(htmlTag);
$vbLabelText   $csharpLabel

Attach the ToHtmlTag() method to the GeneratedBarcode to obtain the HTML tag of the generated barcode. Embed this HTML tag directly into a larger HTML file. For advanced styling options, see our guide on customizing barcode styles.

Why Is HTML Tag Export Better Than External Image References?

HTML tag export provides key advantages over external image references:

  1. No broken image links: Barcode data embeds directly in the tag
  2. Faster rendering: No additional HTTP requests needed
  3. Simplified deployment: No separate image asset management
  4. Better security: No file path or server structure exposure
  5. Dynamic generation: Perfect for real-time barcode creation

Here's a practical web application integration example:

// Generate multiple barcodes for a product catalog
var products = new[] { "PROD-001", "PROD-002", "PROD-003" };
var htmlBuilder = new StringBuilder();

foreach (var productCode in products)
{
    var barcode = BarcodeWriter.CreateBarcode(productCode, BarcodeEncoding.Code128)
        .ResizeTo(200, 50)
        .SetMargins(10);

    htmlBuilder.AppendLine($"<div class='product-barcode'>");
    htmlBuilder.AppendLine($"  <p>Product: {productCode}</p>");
    htmlBuilder.AppendLine($"  {barcode.ToHtmlTag()}");
    htmlBuilder.AppendLine($"</div>");
}
// Generate multiple barcodes for a product catalog
var products = new[] { "PROD-001", "PROD-002", "PROD-003" };
var htmlBuilder = new StringBuilder();

foreach (var productCode in products)
{
    var barcode = BarcodeWriter.CreateBarcode(productCode, BarcodeEncoding.Code128)
        .ResizeTo(200, 50)
        .SetMargins(10);

    htmlBuilder.AppendLine($"<div class='product-barcode'>");
    htmlBuilder.AppendLine($"  <p>Product: {productCode}</p>");
    htmlBuilder.AppendLine($"  {barcode.ToHtmlTag()}");
    htmlBuilder.AppendLine($"</div>");
}
$vbLabelText   $csharpLabel

How Can I Customize the Generated HTML Tag Attributes?

While ToHtmlTag() generates a standard img tag, you can enhance it with additional attributes or custom HTML wrapping. For advanced customization, combine IronBarcode with our styling capabilities:

// Create a customized barcode with specific styling
var customBarcode = BarcodeWriter.CreateBarcode("CUSTOM-123", BarcodeEncoding.Code128)
    .AddAnnotationTextAboveBarcode("Product ID")
    .SetMargins(15)
    .ChangeBackgroundColor(System.Drawing.Color.LightGray);

// Get the HTML tag and add custom attributes
string htmlTag = customBarcode.ToHtmlTag();
string customizedTag = htmlTag.Replace("<img", "<img class='barcode' id='product-123'");
// Create a customized barcode with specific styling
var customBarcode = BarcodeWriter.CreateBarcode("CUSTOM-123", BarcodeEncoding.Code128)
    .AddAnnotationTextAboveBarcode("Product ID")
    .SetMargins(15)
    .ChangeBackgroundColor(System.Drawing.Color.LightGray);

// Get the HTML tag and add custom attributes
string htmlTag = customBarcode.ToHtmlTag();
string customizedTag = htmlTag.Replace("<img", "<img class='barcode' id='product-123'");
$vbLabelText   $csharpLabel

When Should I Choose HTML Tag Over Data URL Format?

Choose HTML tag format when you need:

  • Clean, readable HTML output
  • Easy integration with existing HTML templates
  • Compatibility with HTML editors and CMS systems
  • Direct copy-paste functionality for content creators

HTML tag format works particularly well with Blazor applications where you dynamically inject barcode images into components.

How Do I Save a Barcode as an HTML File?

Save a GeneratedBarcode as an HTML file using the SaveAsHtmlFile() method. The following code demonstrates this method:

:path=/static-assets/barcode/content-code-examples/how-to/ExportBarcodeAsHtmlFile.cs
using IronBarCode;

GeneratedBarcode myBarcode = BarcodeWriter.CreateBarcode("https://ironsoftware.com/csharp/barcode/", BarcodeEncoding.QRCode);
myBarcode.SaveAsHtmlFile("myBarcode.html");
$vbLabelText   $csharpLabel

This method accepts a file path string. The generated HTML file contains the barcode as an HTML tag within proper <html>, <head>, and <body> tags forming a complete HTML file. For complex scenarios with multiple file formats, see our output data formats guide.

Why Generate Complete HTML Files Instead of Fragments?

Complete HTML files offer distinct advantages for specific use cases:

  • Standalone documentation: Generate printable barcode sheets
  • Email attachments: Send self-contained barcode files
  • Archive purposes: Store barcodes with proper structure
  • Testing and debugging: View barcodes independently
  • Batch processing: Generate multiple files for distribution

Here's an example generating a batch of HTML files:

// Generate HTML files for inventory items
public void GenerateInventoryBarcodes(List<InventoryItem> items)
{
    foreach (var item in items)
    {
        var barcode = BarcodeWriter.CreateBarcode(item.SKU, BarcodeEncoding.Code128)
            .AddAnnotationTextBelowBarcode($"{item.Name} - ${item.Price:F2}")
            .ResizeTo(300, 100);

        // Save with descriptive filename
        string filename = $"barcode_{item.SKU}_{DateTime.Now:yyyyMMdd}.html";
        barcode.SaveAsHtmlFile(filename);
    }
}
// Generate HTML files for inventory items
public void GenerateInventoryBarcodes(List<InventoryItem> items)
{
    foreach (var item in items)
    {
        var barcode = BarcodeWriter.CreateBarcode(item.SKU, BarcodeEncoding.Code128)
            .AddAnnotationTextBelowBarcode($"{item.Name} - ${item.Price:F2}")
            .ResizeTo(300, 100);

        // Save with descriptive filename
        string filename = $"barcode_{item.SKU}_{DateTime.Now:yyyyMMdd}.html";
        barcode.SaveAsHtmlFile(filename);
    }
}
$vbLabelText   $csharpLabel

What Are Common Use Cases for HTML File Export?

HTML file export proves valuable in these scenarios:

  1. Retail point-of-sale systems: Generate printable price tags
  2. Warehouse management: Create barcode labels for shelving
  3. Document management: Embed barcodes in reports
  4. Quality control: Generate traceable batch codes
  5. Event management: Create tickets with scannable codes

For high-volume barcode generation, implement async and multithreading to improve performance. When working with specialized formats like QR codes, our C# QR Code Generator tutorial provides comprehensive guidance on creating and customizing QR codes for various business needs.

Frequently Asked Questions

How do I export a barcode as a Data URL in C#?

With IronBarcode, you can export a barcode as a Data URL by using the ToDataUrl() method on a GeneratedBarcode object. Simply create your barcode using BarcodeWriter.CreateBarcode() with your desired value and encoding, then call ToDataUrl() to get the Data URL string that can be embedded directly in HTML.

What are the three HTML export formats available for barcodes?

IronBarcode provides three HTML export formats: Data URL for inline embedding without external files, HTML tag for direct injection into web pages, and complete HTML file for standalone use. Each format serves different integration needs in web applications.

Can I generate an HTML image tag for a barcode with one line of code?

Yes, IronBarcode allows you to generate a fully-formed HTML image tag with a single fluent line of code. Use BarcodeWriter.CreateBarcode() with your barcode value and encoding, then chain the ToHtmlTag() method to get a complete HTML image tag ready for insertion.

When should I use Data URLs instead of traditional image files for barcodes?

Use Data URLs when barcodes are small (under 32KB) and require immediate inline rendering. They're ideal for single-page applications, email templates, offline-capable applications, and dynamic barcode generation scenarios. IronBarcode's ToDataUrl() method makes this conversion seamless.

What barcode formats are supported for HTML export?

IronBarcode supports all its barcode formats for HTML export, including Code 128, QR codes, and many others. The ToDataUrl(), ToHtmlTag(), and HTML file export methods work with all supported barcode formats in the library.

How does using Data URLs improve web application performance?

Data URLs improve performance by embedding barcode image data directly in the HTML document, eliminating separate HTTP requests for image files. This reduces server round-trips and improves page load times, which is particularly beneficial when using IronBarcode for dynamic barcode generation in web applications.

Hairil Hasyimi Bin Omar
Software Engineer
Like all great engineers, Hairil is an avid learner. He’s refining his knowledge of C#, Python, and Java, using that knowledge to add value to team members across Iron Software. Hairil joined the Iron Software team from Universiti Teknologi MARA in Malaysia, where he graduated with a Bachelor's degree ...
Read More
Ready to Get Started?
Nuget Downloads 2,015,591 | Version: 2025.12 just released