使用 IRONBARCODE

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

已更新 2024年1月20日
分享:

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

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


建立 MVC 專案

打開 Microsoft Visual Studio。點擊 Create New Project > 從範本中選擇 ASP.NET Web Application > 按 Next > 為專案命名 > 按 Next > 選擇 MVC > 點擊 Create 按鈕。專案將會按如下所示建立。

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

建立新的 ASP.NET 專案

添加模型

右鍵點擊 Models 資料夾 > 添加 > 類別...

如何在 ASP.NET 中用 C# 打印條碼,圖 2:導航到添加類對話框

導航到添加類別對話框

將出現一個新窗口。將您的類別命名為 BarcodeModel

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

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

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

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
Public Class BarcodeModel
	<Display(Name :="Barcode File Name")>
	Public Property FileName() As String

	<Display(Name := "Barcode Content")>
	Public Property BarcodeContent() As String
End Class
VB   C#

FileName 會用來從使用者那裡取得條碼圖像的名稱。BarcodeContent 用來獲取條碼的內容。

添加控制器

接下來,我們需要向專案中添加一個Controller。它將使用MVC模型與ViewModel進行通信。生成條形碼的程式碼僅由兩三行組成,因此無需單獨的類別,而是將程式碼添加到控制器內。

要添加控制器,右鍵點擊Controllers資料夾 > Add > Controller。新的視窗將會彈出。選擇MVC 5 Controller Empty,然後點擊Add按鈕。新的框將會出現。

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

新增控制器對話方塊

請輸入控制器名稱,例如 BarcodeController。 點擊「新增」按鈕。將生成一個新的控制器。

下一步是安裝條碼庫。

安裝條碼庫

IronBarcode 庫被推薦為生成條碼的第三方庫。它免費供開發使用,並提供多種功能來自定義條碼,例如添加 將標誌轉換為條碼圖像在條碼下方或上方添加數值, 在條碼上方或下方添加註解調整條碼大小,將條碼儲存到 多種圖像格式等等。欲了解更多詳情,請點擊此處。

前往程序包管理器控制台。鍵入以下命令並按下回車鍵。

Install-Package BarCode

此命令將在專案中安裝 IronBarcode 程式庫。

生成條碼

接下來,將以下範例代碼添加到控制器。

[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path, model.FileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path, model.FileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
<HttpPost>
Public Function CreateBarcode(ByVal model As BarcodeModel) As ActionResult
	Try
		Dim MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128)
		Dim path As String = Server.MapPath("~/Files/")
		Dim filepath As String = System.IO.Path.Combine(path, model.FileName)
		MyBarCode.AddBarcodeValueTextAboveBarcode()
		MyBarCode.SaveAsJpeg(filepath)
		Dim image As String = Directory.GetFiles(path).FirstOrDefault()
		ViewBag.fileName = image
		Return View()
	Catch
		Return View()
	End Try
End Function
VB   C#

try-catch 用於捕捉任何執行時例外。

CreateBarcode 函數提供 BarcodeWriter 類別採用兩個參數:條碼內容和編碼方案。此外,它還接受其他11個可選參數,包括最大高度、最大寬度等等。

Server.MapPath 函數用於映射生成的條碼圖像將被保存的路徑。Path.Combine 方法將路徑和條碼圖像名稱結合起來。

在條碼上方添加條碼值文字 此功能將添加條碼值。IronBarcode 提供其他條碼設置,例如 max-heightmax-widthbarcodecolor 等。您可以探索並使用各種參數。 SaveAsJpeg 函數以路徑作為參數,並將生成的條碼保存在該特定路徑中。

Directory.GetFile 方法將獲取新生成的條碼圖像。

ViewBag.FileName 用於將條碼圖像的路徑傳送到視圖中以顯示生成的條碼圖像。

通過將編碼方案從 Code128 更改為 QR 碼,也可以生成 QR 碼。 QRCode.

添加檢視

接下來的步驟是為這個 ASP.NET Web 應用程式提供客戶端,方法是新增一個新的檢視。在控制器方法的名稱上點擊右鍵,然後點擊「添加檢視」按鈕。

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

導航到添加視圖對話框

將會出現一個新視窗。選擇MVC 5視圖,然後點擊添加按鈕。

將出現一個新的提示,如下所示。

如何在C#中的ASP.NET中打印條碼,圖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")
}
model ReadOnly Property () As GenerateBarcodeMVC.Models.BarcodeModel
ViewBag.DisplayBarcode = False
End Property

'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Create</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Html.AntiForgeryToken() <div class="form-horizontal"> (Of h4) GenerateBarcode</h4> <hr /> Html.ValidationSummary(True, "", New With {Key .class = "text-danger"}) <div class="form-group"> Html.LabelFor(Function(model) model.FileName, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.FileName, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.FileName, "", New With {Key .class = "text-danger"}) </div> </div> <div class="form-group"> Html.LabelFor(Function(model) model.BarcodeContent, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.BarcodeContent, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.BarcodeContent, "", New With {Key .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>
End If
Dim Scripts As section
If True Then
Scripts.Render("~/bundles/jqueryval")
End If
VB   C#

接著,在視圖內按右鍵,然後點選「Run to Browser」按鈕。

輸出

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

運行 Web 應用程式以顯示創建表單

輸入您的條形碼圖像名稱和條形碼內容,如下所示:

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

輸入您的條碼內容

點擊 創建 按鈕。條碼圖像將生成並顯示在如下所示的屏幕上。

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

從 URL 生成條碼

摘要

本教程演示了如何使用 C# 中的 ASP.NET 結合 MVC 框架生成條碼。 微軟 Visual Studio 用作 IDE。 IronPDF 是一個第三方庫,免費供開發使用,並且與所有版本的 .NET 框架兼容,包括新發布的版本。 IronBarcode 快速且提供多種處理條碼的功能。 它還可以 生成 QR 碼 指定不同的類型。

還有其他許多有用的庫,例如與 PDF 文件一起使用的 IronPDF、與 Excel 文件一起使用的 IronXL 以及用於 OCR 的 IronOCR。目前,您可以通過購買完整的 Iron Suite,以兩個庫的價格獲得所有五個庫。訪問 我們的授權頁面 了解更多詳情。

< 上一頁
如何在 C# Windows 應用程式中生成 QR 碼
下一個 >
條碼生成器 .NET 教程

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 1,203,227 查看許可證 >