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

如何在 C# 中將 BarCode 匯出為 HTML

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

IronBarcode 讓 C# 開發人員能夠將生成的 BarCode 以三種 HTML 格式匯出:用於內嵌的 Data URL、用於直接插入的 HTML 標籤,或是用於獨立使用的完整 HTML 檔案——提供多樣化的整合選項,且無需外部依賴項。

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

只需一行流暢的程式碼,即可生成 BARCODE 並直接將其匯出為完整的 HTML 圖片標籤。 無需管理外部圖像檔案或資產依賴項,即可快速上手。

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/BarCode

    PM > Install-Package BarCode
  2. 請複製並執行此程式碼片段。

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

    立即透過免費試用,在您的專案中開始使用 IronBarcode

    arrow pointer

如何將 BarCode 匯出為資料 URL?

在將 BarCode 匯出為 Data URL 之前,請先了解何謂 Data URL。 資料 URL(亦稱為資料 URI)是一種將資料直接嵌入 URL 字串中的統一資源識別碼。 這使得資料能在網頁中內嵌顯示,彷彿是外部資源一般。 資料 URL 支援任何格式:文字、圖片、音訊、影片及二進位資料。 請將取得的 Data URL 作為 src 屬性,置於 HTML 中的 image 標籤內。 以下是將 GeneratedBarcode 轉換為 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);
Imports IronBarCode
Imports System

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

使用 BarcodeWriter 類別中的 CreateBarcode() 方法,並將 BARCODE 值與編碼作為參數,來建立 BARCODE。 透過將 ToDataUrl() 方法附加至 GeneratedBarcode,即可取得資料 URL。 此方法適用於 IronBarcode 支援的所有 BARCODE 格式

為何在網頁應用程式中使用資料 URL 如此重要?

Data URL 透過減少 HTTP 請求並提升頁面載入效能,為網頁應用程式帶來顯著優勢。 當您將 BarCode 嵌入為 Data URL 時,圖像資料將成為 HTML 文件本身的一部分,從而省去額外的圖像檔案請求。 這將帶來以下好處:

  • 僅需極少伺服器往返的單頁應用程式 (SPAs)
  • 外部圖片可能被封鎖的電子郵件範本
  • 具備離線功能的應用程式,可在無網路連線的情況下運作
  • 動態BarCode生成,當建立實體檔案效率不彰時

關於生產環境部署,請參閱我們關於部署至 AzureAWS 的指南,以實現基於雲端的 BarCode 生成。

何時應使用資料 URL 取代圖片檔案?

當BarCode尺寸較小(小於 32KB)且需要立即內聯渲染時,請使用 Data URLs。 在以下情況下,請選擇儲存於伺服器或 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
}
' Example: Choosing between Data URL and file export based on size
Dim barcode As GeneratedBarcode = BarcodeWriter.CreateBarcode("LARGE-DATA-STRING-HERE", BarcodeEncoding.PDF417)

' Check estimated size before choosing export method
If barcode.BinaryStream.Length < 32768 Then ' 32KB threshold
    ' Use Data URL for smaller barcodes
    Dim dataUrl As String = barcode.ToDataUrl()
    ' Embed directly in HTML
Else
    ' Save as file for larger barcodes
    barcode.SaveAsImage("large-barcode.png")
    ' Reference as external resource
End If
$vbLabelText   $csharpLabel

Data URL 的大小限制為何?

雖然現代瀏覽器在技術上支援數百萬位元的 Data URL,但實際上仍存在限制:

  • Internet Explorer 8:限 32KB
  • 現代瀏覽器:支援 2-4MB,但效能會下降
  • 行動瀏覽器:受記憶體限制影響,限制條件更為嚴格
  • 電子郵件客戶端:將 Data URL 限制在 8-64KB 之間

為獲得最佳效能,請將 Data URL BarCode 大小控制在 32KB 以下。 若需處理較大的BarCode或生成多個BarCode,請使用我們的"匯出為串流"功能,以實現高效的記憶體管理。

如何將 BarCode 匯出為 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);
Imports IronBarCode
Imports System

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

ToHtmlTag() 方法附加至 GeneratedBarcode,以取得生成的 BARCODE 之 HTML 標籤。 請將此 HTML 標籤直接嵌入較大的 HTML 檔案中。如需進階樣式設定選項,請參閱我們的 BarCode 樣式自訂指南。

為何 HTML 標籤匯出比外部圖片引用更佳?

相較於外部圖片引用,HTML 標籤匯出具備以下關鍵優勢:

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

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

// 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>");
}
Imports System.Text

' Generate multiple barcodes for a product catalog
Dim products = New String() {"PROD-001", "PROD-002", "PROD-003"}
Dim htmlBuilder = New StringBuilder()

For Each productCode In products
    Dim 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>")
Next
$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'");
' Create a customized barcode with specific styling
Dim 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
Dim htmlTag As String = customBarcode.ToHtmlTag()
Dim customizedTag As String = htmlTag.Replace("<img", "<img class='barcode' id='product-123'")
$vbLabelText   $csharpLabel

何時應選擇 HTML 標籤而非資料 URL 格式?

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

  • 簡潔、易讀的 HTML 輸出
  • 可輕鬆整合至現有的 HTML 模板
  • 與 HTML 編輯器及內容管理系統 (CMS) 的相容性
  • 為內容創作者提供直接複製貼上的功能

HTML 標籤格式特別適用於 Blazor 應用程式,您可以在其中將 BarCode 圖像動態注入元件中。

如何將 BarCode 儲存為 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");
Imports IronBarCode

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

此方法接受一個檔案路徑字串。 生成的 HTML 檔案將 BARCODE 作為 HTML 標籤,置於適當的 <head><body> 標籤內,形成完整的 HTML 檔案。若涉及多種檔案格式的複雜情境,請參閱我們的輸出資料格式指南

為何要產生完整的 HTML 檔案而非片段?

完整的 HTML 檔案在特定使用情境下具有顯著優勢:

  • 獨立文件:產生可列印的BarCode表
  • 電子郵件附件:傳送獨立的 BARCODE 檔案
  • 存檔用途:以正確結構儲存BarCode
  • 測試與除錯:獨立檢視 BARCODE
  • 批次處理:產生多個檔案以供分發

以下是一個生成一批 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);
    }
}
' Generate HTML files for inventory items
Public Sub GenerateInventoryBarcodes(items As List(Of InventoryItem))
    For Each item In items
        Dim barcode = BarcodeWriter.CreateBarcode(item.SKU, BarcodeEncoding.Code128) _
            .AddAnnotationTextBelowBarcode($"{item.Name} - ${item.Price:F2}") _
            .ResizeTo(300, 100)

        ' Save with descriptive filename
        Dim filename As String = $"barcode_{item.SKU}_{DateTime.Now:yyyyMMdd}.html"
        barcode.SaveAsHtmlFile(filename)
    Next
End Sub
$vbLabelText   $csharpLabel

HTML 檔案匯出的常見應用情境有哪些?

在以下情境中,HTML 檔案匯出功能極具價值:

  1. 零售銷售點系統:生成可列印的價格標籤
  2. 倉儲管理:為上架作業建立BarCode標籤
  3. 文件管理:在報告中嵌入BarCode
  4. 品質控制:產生可追溯的批次代碼
  5. 活動管理:建立附有可掃描條碼的門票

針對大量BarCode生成,請實作非同步與多執行緒機制以提升效能。 若需處理 QR 碼等特殊格式,我們的 C# QR 碼產生器教學指南將提供全面指引,協助您根據各種商業需求建立並自訂 QR 碼。

常見問題

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

使用IronBarcode,您可以使用ToDataUrl()方法在GeneratedBarcode物件上匯出條碼為資料URL。只需使用BarcodeWriter.CreateBarcode()創建條碼,設定您的值與編碼,然後調用ToDataUrl()即可獲取可直接嵌入HTML的資料URL字串。

可用的條碼三種HTML匯出格式是什麼?

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

我可以用一行代碼生成條碼的HTML圖像標籤嗎?

可以,IronBarcode允許您用簡單順暢的一行代碼生成完整的HTML圖像標籤。使用BarcodeWriter.CreateBarcode()設定條碼值與編碼,然後鏈接ToHtmlTag()方法即可獲取適合插入的完整HTML圖像標籤。

什麼時候應使用資料URL而不是傳統圖像檔案用於條碼?

當條碼較小(小於32KB)並需要即時內嵌渲染時可使用資料URL。它們非常適合單頁面應用程式、電子郵件模板、支持離線的應用程式,以及動態條碼生成情境。IronBarcode的ToDataUrl()方法使此轉換變得順利。

支援哪些條碼格式的HTML匯出?

IronBarcode支援所有條碼格式的HTML匯出,包括Code 128、QR碼等。ToDataUrl()、ToHtmlTag()和HTML檔案匯出方法適用於程式庫中所有支援的條碼格式。

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

資料URL通過將條碼圖像數據嵌入HTML文件中,消除了對圖像檔案獨立HTTP請求,提高了效能。這可以減少服務器回合次數並改善頁面加載時間,特別是在使用IronBarcode進行動態條碼生成的網頁應用程式中具有益處。

IronBarcode是否提供自定義條碼外觀的支持?

是的,IronBarcode提供了廣泛的條碼外觀自定義選項,包括顏色、大小和文字註釋,讓您可以根據具體設計需求定制條碼。

IronBarcode如何幫助改善業務流程效率?

IronBarcode通過使條碼生成和讀取快速且準確來提高業務流程效率,減少手動數據輸入錯誤,並改善庫存和資產追蹤。

將IronBarcode實現於專案中需要什麼程式設計技能?

基本的C#程式設計知識足以將IronBarcode實現於專案中,因為它提供了簡單的方法和全面的文檔來指導開發者。

IronBarcode適合於小型專案和大型企業應用嗎?

IronBarcode設計為可擴展且多功能,使其適合小型專案和需要強大條碼解決方案的大型企業應用。

Hairil Hasyimi Bin Omar
軟體工程師
如同所有傑出的工程師,Hairil 是一位熱衷學習的人。他正不斷精進自己在 C#、Python 和 Java 方面的知識,並運用這些知識為 Iron Software 的團隊成員創造價值。Hairil 從馬來西亞馬拉科技大學(Universiti Teknologi MARA)加入 Iron Software 團隊,他在該校取得化學與製程工程學士學位。
準備好開始了嗎?
Nuget 下載 2,240,258 | 版本: 2026.5 just released
Still Scrolling Icon

還在捲動嗎?

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