跳過到頁腳內容
使用IRONBARCODE
如何在 ASP.NET 中列印 BarCode

如何在ASP.NET C#中打印條碼

本文將示範如何使用 C# 在 ASP.NET Web 應用程式中列印條碼影像。 本範例將使用 MVC 框架,但您也可以根據需要使用 ASP.NET Web Forms、Windows Forms 或 Web API。

對 ASP.NET MVC 框架有基本的了解將有助於您更好地理解本文。


建立一個 MVC 項目

開啟 Microsoft Visual Studio。 點選"建立新專案" > 從範本中選擇 ASP.NET Web 應用程式 > 按下"下一步" > 為專案命名 > 按下"下一步" > 選擇 MVC > 點選"建立"按鈕。 項目將按如下所示建立。

如何在 ASP.NET 中使用 C# 列印條碼,圖 1:建立一個新的 ASP.NET 項目 建立一個新的 ASP.NET 項目

新增模型

右鍵點選"模型"資料夾 >新增>類別...

如何在 ASP.NET 中使用 C# 列印條碼,圖 2:導覽至新增類別對話框 導航至新增類別對話框

將出現一個新視窗。 將你的類別命名為BarcodeModel

在模型類別中編寫以下程式碼。

using System.ComponentModel.DataAnnotations;

public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string FileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
using System.ComponentModel.DataAnnotations;

public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string FileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
Imports System.ComponentModel.DataAnnotations

Public Class BarcodeModel
	<Display(Name :="Barcode File Name")>
	Public Property FileName() As String

	<Display(Name := "Barcode Content")>
	Public Property BarcodeContent() As String
End Class
$vbLabelText   $csharpLabel

FileName將用於從使用者取得條碼圖像名稱。 BarcodeContent用於取得條碼的內容。

新增控制器

接下來,在專案中新增一個Controller 。 它將使用 MVC 模型與ViewModel進行通訊。 產生條碼的程式碼僅由兩三行組成。 因此,沒有必要單獨設立一個類別; 相反,代碼被添加到控制器內部。

若要新增控制器,請右鍵點選"控制器"資料夾 >新增>控制器。 將出現一個新視窗。 選擇 MVC 5 控制器為空。 點擊"新增"按鈕。 將出現一個新框。

如何在 ASP.NET 中使用 C# 列印條碼,圖 3:新增控制器對話框 新增控制器對話框

請填寫您的控制器名稱,例如BarcodeController 。 點擊"新增"按鈕。 將產生一個新的控制器。

下一步是安裝條碼庫。

安裝條碼庫

建議使用 IronBarcode 函式庫作為產生條碼的第三方函式庫。 它可免費用於開發,並提供多種條碼自訂功能,例如在條碼圖像上添加徽標、在條碼下方或上方添加數值、在條碼下方或上方添加註釋、調整條碼大小、將條碼保存為多種圖像格式等。更多詳情,請點擊此處。

前往軟體包管理器控制台。 輸入以下指令並按下回車鍵。

Install-Package BarCode

此指令會將 IronBarcode 庫安裝到專案中。

產生條碼

接下來,將以下範例程式碼新增至控制器。

using System.IO;
using System.Linq;
using System.Web.Mvc;
using IronBarCode;

public class BarcodeController : Controller
{
    [HttpPost]
    public ActionResult CreateBarcode(BarcodeModel model)
    {
        try
        {
            // Create a barcode with the specified content and encoding
            var MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);

            // Define the path where the barcode image will be saved
            string path = Server.MapPath("~/Files/");
            string filepath = Path.Combine(path, model.FileName);

            // Add the barcode value text above the barcode
            MyBarCode.AddBarcodeValueTextAboveBarcode();

            // Save the generated barcode as a JPEG file
            MyBarCode.SaveAsJpeg(filepath);

            // Retrieve the first file from the directory as a sample image
            string image = Directory.GetFiles(path).FirstOrDefault();

            // Pass the image path to the view
            ViewBag.FileName = image;
            return View();
        }
        catch
        {
            // Handle any exceptions that occur
            return View();
        }
    }
}
using System.IO;
using System.Linq;
using System.Web.Mvc;
using IronBarCode;

public class BarcodeController : Controller
{
    [HttpPost]
    public ActionResult CreateBarcode(BarcodeModel model)
    {
        try
        {
            // Create a barcode with the specified content and encoding
            var MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);

            // Define the path where the barcode image will be saved
            string path = Server.MapPath("~/Files/");
            string filepath = Path.Combine(path, model.FileName);

            // Add the barcode value text above the barcode
            MyBarCode.AddBarcodeValueTextAboveBarcode();

            // Save the generated barcode as a JPEG file
            MyBarCode.SaveAsJpeg(filepath);

            // Retrieve the first file from the directory as a sample image
            string image = Directory.GetFiles(path).FirstOrDefault();

            // Pass the image path to the view
            ViewBag.FileName = image;
            return View();
        }
        catch
        {
            // Handle any exceptions that occur
            return View();
        }
    }
}
Imports System.IO
Imports System.Linq
Imports System.Web.Mvc
Imports IronBarCode

Public Class BarcodeController
	Inherits Controller

	<HttpPost>
	Public Function CreateBarcode(ByVal model As BarcodeModel) As ActionResult
		Try
			' Create a barcode with the specified content and encoding
			Dim MyBarCode = BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128)

			' Define the path where the barcode image will be saved
			Dim path As String = Server.MapPath("~/Files/")
			Dim filepath As String = System.IO.Path.Combine(path, model.FileName)

			' Add the barcode value text above the barcode
			MyBarCode.AddBarcodeValueTextAboveBarcode()

			' Save the generated barcode as a JPEG file
			MyBarCode.SaveAsJpeg(filepath)

			' Retrieve the first file from the directory as a sample image
			Dim image As String = Directory.GetFiles(path).FirstOrDefault()

			' Pass the image path to the view
			ViewBag.FileName = image
			Return View()
		Catch
			' Handle any exceptions that occur
			Return View()
		End Try
	End Function
End Class
$vbLabelText   $csharpLabel

try-catch用於捕獲任何運行時異常。

  • BarcodeWriter類別提供的CreateBarcode函數接受兩個參數:條碼內容和編碼方案。 此外,它還接受 11 個其他可選參數,包括最大高度、最大寬度等等。
  • Server.MapPath函數用於對應產生的條碼影像的儲存路徑。 Path.Combine方法會將路徑和條碼影像名稱合併在一起。
  • AddBarcodeValueTextAboveBarcode函數會加入條碼值。 IronBarcode 還提供其他條碼設置,例如max-heightmax-widthbarcodecolor等。 您可以探索和利用各種參數。
  • SaveAsJpeg函數接受路徑作為參數,並將產生的條碼儲存到該特定路徑中。
  • Directory.GetFiles方法將取得新產生的條碼映像。
  • ViewBag.FileName用於將條碼影像的路徑傳送至視圖,以便顯示產生的條碼影像。

也可以將編碼方案從Code128改為QRCode來產生二維碼。

新增視圖

下一步是透過新增視圖來為該 ASP.NET Web 應用程式提供用戶端。 右鍵單擊控制器方法的名稱,然後按一下"新增視圖"按鈕。

如何在 ASP.NET 中使用 C# 列印條碼,圖 4:導覽至新增視圖對話框 導航至"新增視圖對話框"

將出現一個新視窗。 選擇 MVC 5 視圖,然後按一下"新增"按鈕。

將會顯示如下所示的新提示。

如何在 ASP.NET 中使用 C# 列印條碼,圖 5:新增視圖對話框 新增視圖對話框

為您的視圖命名,然後按一下"新增"按鈕。 將會建立一個新的.cshtml檔。

將以下程式碼新增至新產生的視圖。

@model GenerateBarcodeMVC.Models.BarcodeModel

@{
    ViewBag.DisplayBarcode = false;
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>GenerateBarcode</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BarcodeContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BarcodeContent, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BarcodeContent, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <img src="~/Files/@Path.GetFileName(ViewBag.FileName)" alt="Barcode" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
@model GenerateBarcodeMVC.Models.BarcodeModel

@{
    ViewBag.DisplayBarcode = false;
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>GenerateBarcode</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.BarcodeContent, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.BarcodeContent, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.BarcodeContent, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <img src="~/Files/@Path.GetFileName(ViewBag.FileName)" alt="Barcode" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
HTML

接下來,在視圖中按一下滑鼠右鍵,然後按一下"執行到瀏覽器"按鈕。

輸出

如何在 ASP.NET 中使用 C# 列印條碼,圖 6:執行 Web 應用程式以顯示建立表單 運行 Web 應用程式以顯示建立表單

請按如下所示輸入條碼圖像名稱和條碼內容:

如何在 ASP.NET 中使用 C# 列印條碼,圖 7:輸入條碼內容 輸入條碼內容

點擊"創建"按鈕。 條碼影像將產生並顯示在螢幕上,如下圖所示。

如何在 ASP.NET 中使用 C# 列印條碼,圖 8:從 URL 產生條碼 從 URL 產生條碼

摘要

本教學示範如何使用 ASP.NET 和 C# 以及 MVC 框架產生條碼。 我們使用 Microsoft Visual Studio 作為整合開發環境 (IDE)。 IronPDF 是一個第三方函式庫,可免費用於開發,並且相容於所有版本的 .NET Framework,包括最新發布的版本。 IronBarcode 速度快,並提供多種條碼處理功能。 它還可以透過指定不同類型的二維碼來產生二維碼

還有許多其他有用的程式庫,例如用於處理 PDF 文件的 IronPDF、用於處理 Excel 文件的 IronXL 和用於處理 OCR 的 IronOCR。 現在購買完整的 Iron Suite 套裝,即可享受僅需兩個庫的價格獲得全部五個庫。請造訪我們的授權頁面以了解更多詳情。

常見問題解答

如何在 ASP.NET MVC 中使用 C# 生成并打印条形码图像?

您可以使用 IronBarcode library 在 ASP.NET MVC 應用程式中產生和列印條碼影像。這需要建立一個 MVC 專案,透過套件管理員控制台安裝 IronBarcode,並使用 `BarcodeWriter.CreateBarcode` 方法產生條碼。

為條碼列印建立一個新的 MVC 專案需要哪些步驟?

若要為條碼列印建立新的 MVC 專案,請開啟 Microsoft Visual Studio,選擇「建立新專案」,選擇「ASP.NET Web 應用程式」,並從可用範本中選擇「MVC」。

如何安裝 IronBarcode 函式庫以在 C# 中產生條碼?

在 Visual Studio 中開啟套件管理員控制台並執行指令,安裝 IronBarcode 函式庫:Install-Package IronBarcode

如何在 C# 中保存生成的 BarCode 圖像?

您可以使用 IronBarcode 提供的 `SaveAsJpeg` 方法保存生成的条码图像,指定保存图像的文件路径。

我可以在 ASP.NET 應用程式中自訂 BarCode 影像嗎?

是的,IronBarcode 允許自定義條碼圖片,包括添加標誌、註釋以及更改大小和尺寸以滿足您的需求。

如何在 MVC 視圖中顯示產生的 BarCode?

若要在 MVC 視圖中顯示產生的條碼,請在專案中建立一個 View,並使用 `ViewBag` 將條碼影像的路徑傳給 View。這樣就可以在客戶端顯示條碼。

如果在生成 BarCode 的過程中遇到錯誤,該怎麼辦?

在您的 C# 程式碼中使用 try-catch 區塊來處理條碼產生過程中可能發生的任何執行時異常,以確保穩健的錯誤處理。

是否可以使用與 BarCode 相同的方法產生 QR 碼?

是的,通過使用 IronBarcode,您可以在 `BarcodeWriter.CreateBarcode` 方法中將編碼方案設置為 `QRCode`,從而生成 QR 代碼。

文件管理方面還有哪些 Iron 軟體函式庫值得推薦?

除 IronBarcode 外,Iron Software 還提供其他庫,如 IronPDF、IronXL 和 IronOCR。這些函式庫為文件管理任務提供全面的解決方案。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。