如何在 C# 中將條碼創建為 HTML

如何在 C# 中將條碼匯出為 HTML

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronBarcode可讓 C# 開發人員以三種格式將產生的條碼匯出為 HTML:用於內嵌嵌入的資料 URL、用於直接注入的 HTML 標籤或用於獨立使用的完整 HTML 檔案——提供多樣化的整合選項,而無需外部相依性。

快速入門:一行程式碼即可將條碼匯出為 HTML 標籤

使用一行流暢的程式碼,即可產生條碼並直接匯出為完整的 HTML 影像標籤。 無需管理外部影像檔案或資源依賴項,即可快速上手。

  1. 使用NuGet套件管理器安裝https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 複製並運行這段程式碼。

    var htmlTag = BarcodeWriter.CreateBarcode("1234567890", BarcodeWriterEncoding.Code128).ToHtmlTag();
  3. 部署到您的生產環境進行測試

    今天就在您的專案中開始使用免費試用IronBarcode

    arrow pointer

如何將條碼導出為資料URL?

在將條碼匯出為資料 URL 之前,請先了解什麼是資料 URL。 資料 URL (也稱為資料 URI )是一種統一資源標識符,它將資料直接嵌入到 URL 字串中。 這樣就可以在網頁中以內聯方式顯示數據,就好像數據是外部資源一樣。 資料 URL 支援任何格式:文字、圖像、音訊、視訊和二進位資料。 在 HTML 中,將取得的資料 URL 用作圖像標籤內的 src 屬性。 以下是如何將錯誤代碼 409 轉換為資料 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

使用 BarcodeWriter 類別的 CreateBarcode() 方法,以條碼值和編碼作為參數建立條碼。 透過將 ToDataUrl() 方法附加到 GeneratedBarcode 來取得資料 URL 。 這種方法適用於IronBarcode中所有支援的條碼格式

為什麼使用資料 URL 對 Web 應用程式很重要?

資料 URL 透過減少 HTTP 請求和提高頁面載入效能,為 Web 應用程式提供了顯著優勢。 當您將條碼嵌入為資料 URL 時,圖像資料將成為 HTML 文件本身的一部分,從而無需單獨請求圖像檔案。 這樣做的好處有:

  • 需要最少伺服器往返次數的單頁應用程式 (SPA)
  • 可能屏蔽外部圖片的電子郵件模板
  • 無需網路連接即可離線運行的應用程式
  • 在建立實體檔案效率低的情況下,動態產生條碼

對於生產環境部署,請參閱我們關於部署到 AzureAWS以進行基於雲端的條碼產生的指南。

何時應該使用數據URL而不是圖像文件?

當條碼較小(小於 32KB)且需要立即內聯渲染時,請使用資料 URL。 在下列情況下選擇儲存在伺服器或 CDN 上的傳統影像檔案:

// 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

資料URL的大小限制是什麼?

雖然現代瀏覽器在技術上支援幾兆位元組的資料URL,但實際應用中仍存在一些限制:

  • Internet Explorer 8 :限制為 32KB -現代瀏覽器:支援 2-4MB 內存,但效能會下降 -行動瀏覽器:由於記憶體限制,限制更為嚴格 -電子郵件用戶端:將資料 URL 限制為 8-64KB

為獲得最佳效能,請將資料 URL 條碼保持在 32KB 以下。 對於較大的條碼或多個條碼的生成,請使用我們的串流導出功能以進行高效的記憶體管理。

如何將條碼匯出為 HTML 標籤?

使用 ToHtmlTag() 方法將 GeneratedBarcode 匯出為 HTML。 此方法將 GeneratedBarcode 物件渲染為完全成型的 HTML 標籤,以便直接注入 HTML 中,而無需JavaScript、CSS 或影像相依性。 以下程式碼示範如何匯出 HTML 標籤:

: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

ToHtmlTag() 方法附加到 GeneratedBarcode,以取得產生的條碼的 HTML 標籤。 將此 HTML 標籤直接嵌入到較大的 HTML 檔案中。有關進階樣式選項,請參閱我們的條碼樣式自訂指南。

為什麼HTML標籤匯出比外部影像引用更好?

HTML標籤匯出相比外部圖片引用具有以下主要優勢:

1.無失效圖片連結:條碼資料直接嵌入標籤中 2.渲染速度更快:無需額外的 HTTP 請求 3.簡化部署:無需單獨的鏡像資產管理 4.安全性更高:不會暴露檔案路徑或伺服器結構 5.動態生成:非常適合即時創建條碼

以下是一個實際的Web應用程式整合範例:

// 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

如何自訂產生的HTML標籤屬性?

雖然 ToHtmlTag() 產生一個標準的 img 標籤,但您可以透過新增屬性或自訂 HTML 包裝來增強它。 如需進行進階自訂,請將IronBarcode與我們的樣式功能結合使用:

// 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

何時應該選擇HTML標籤而不是資料URL格式?

需要時請選擇 HTML 標籤格式:

  • 簡潔易讀的 HTML 輸出
  • 輕鬆與現有 HTML 範本集成
  • 與 HTML 編輯器和 CMS 系統相容
  • 為內容創作者提供直接複製貼上功能

HTML 標籤格式與Blazor應用程式搭配使用效果尤佳,您可以在 Blazor 應用程式中動態地將條碼圖片注入到元件中。

如何將條碼儲存為HTML檔案?

使用 SaveAsHtmlFile() 方法將 GeneratedBarcode 儲存為 HTML 檔案。 以下程式碼演示了這種方法:

: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

此方法接受一個檔案路徑字串。 產生的 HTML 檔案包含條碼,條碼以 HTML 標籤的形式包含在正確的 <head><body> 標籤內,從而構成一個完整的 HTML 檔案。對於涉及多種文件格式的複雜情況,請參閱我們的輸出資料格式指南

為什麼要產生完整的 HTML 檔案而不是片段?

完整的HTML檔案在特定應用場景下具有明顯的優勢:

-獨立文件:產生可列印的條碼表 -電子郵件附件:發送獨立的條碼文件 -存檔用途:以適當的結構儲存條碼 -測試與調試:獨立查看條碼 -批次處理:產生多個文件以供分發

以下範例示範如何批次產生 HTML 檔案:

// 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

HTML文件匯出的常見用例有哪些?

在以下情況下,匯出HTML檔案非常有用:

1.零售POS系統:產生可列印的價格標籤 2.倉庫管理:建立貨架條碼標籤 3.文件管理:在報告中嵌入條碼 4.品質控制:產生可追溯的批號 5.活動管理:建立可掃描條碼的門票

對於大批量條碼生成,實現非同步和多執行緒以提高效能。 在使用二維碼等特殊格式時,我們的C# 二維碼產生器教學提供了創建和自訂二維碼以滿足各種業務需求的全面指導。

常見問題解答

如何在 C# 中將 BarCode 匯出為資料 URL?

使用 IronBarcode,您可以在 GeneratedBarcode 物件上使用 ToDataUrl() 方法將條碼匯出為 Data URL。只需使用BarcodeWriter.CreateBarcode()使用您所需的值和编碼创建您的條形碼,然後調用ToDataUrl()来獲取數据URL字符串,該字符串可以直接嵌入到HTML中。

BarCode 有哪三種 HTML 匯出格式?

IronBarcode 提供三種 HTML 匯出格式:無需外部檔案即可內嵌的資料 URL、直接注入網頁的 HTML 標籤,以及獨立使用的完整 HTML 檔案。每種格式都能滿足網頁應用程式中不同的整合需求。

我可以用一行代碼為 BarCode 產生 HTML 圖片標籤嗎?

是的,IronBarcode 允許您用一行流暢的程式碼來產生一個完整的 HTML 圖像標籤。使用 BarcodeWriter.CreateBarcode() 加上您的條碼值和編碼,然後鏈結 ToHtmlTag() 方法來獲得一個完整的 HTML 圖像標籤,準備插入。

何時應該使用資料 URL 而非傳統的圖像檔案來處理 BarCode?

當條碼較小(32KB 以下)且需要立即內嵌渲染時,請使用資料 URL。它們是單頁應用程序,電子郵件模板,離線應用程序和動態條碼生成方案的理想選擇。IronBarcode的ToDataUrl()方法使得这种轉换天衣無缝。

HTML 匯出支援哪些 BarCode 格式?

IronBarcode 支援其所有條碼格式的 HTML 匯出,包括 Code 128、QR Code 以及許多其他格式。ToDataUrl()、ToHtmlTag()和HTML文件導出方法可與庫中所有支援的條碼格式一起使用。

使用資料 URL 如何改善網路應用程式效能?

資料 URL 透過直接在 HTML 文件中嵌入 BarCode 影像資料來改善效能,省去了影像檔案的單獨 HTTP 請求。這減少了伺服器的往返次數,並改善了頁面載入時間,這對於在 Web 應用程式中使用 IronBarcode 進行動態條碼生成尤其有利。

Hairil Hasyimi Bin Omar
軟體工程師
和所有优秀的工程师一样,Hairil 是個努力学习者。他正在细化自己的 C# 、Python 和 Java 知识,将这些知识應用于 Iron Software 各個团队成员以增加价值。Hairil 自马来西亚 Universiti Teknologi MARA 加入 Iron Software 团队,并以化学与工艺工程学士学位毕业。
準備好開始了嗎?
Nuget 下載 2,108,094 | 版本: 2026.3 剛剛發布
Still Scrolling Icon

還在捲動嗎?

想要快速證明? PM > Install-Package BarCode
執行範例 看您的字串變成 BarCode。