使用 IRONBARCODE

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

喬迪·巴迪亞
喬迪·巴迪亞
2022年6月25日
已更新 2024年1月20日
分享:

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

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


建立一個MVC專案

打開 Microsoft Visual Studio。 點擊建立新專案 > 從模板中選擇 ASP.NET Web 應用程式 > 按下一步 > 給你的專案命名 > 按下一步 > 選擇 MVC > 點擊建立按鈕。 該專案將按如下所示創建。

如何在 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
$vbLabelText   $csharpLabel

FileName 將用於從用戶獲取條碼圖像名稱。 BarcodeContent 用於獲取條碼的內容。

新增控制器

接下來,向專案中新增一個Controller。 它將使用 MVC 模型與 ViewModel 進行通信。 生成條形碼的代碼只需兩到三行。 因此,無需單獨的類別; 相反,代碼被添加到控制器內。

若要新增控制器,請在 Controllers 資料夾上按右鍵 > 新增 > 控制器。 將會出現一個新視窗。 選擇 MVC 5 控制器空白。 點擊添加按鈕。 將出現一個新框。

如何在ASP.NET的C#中打印條碼,圖3:添加控制器對話框

新增控制器對話框

寫下您的控制器名稱,例如 BarcodeController。 單擊「新增」按鈕。 將生成一個新的控制器。

接下來的步驟是安裝條碼庫。

安裝條碼庫

IronBarcode 庫建議作為生成條形碼的第三方庫。 它是免費的開發工具,並提供多種功能來自訂條碼,例如在條碼圖像中添加標誌、在條碼下方或上方添加值、在條碼下方或上方添加註釋、調整條碼大小、將條碼保存為多種圖像格式等。欲了解更多詳情,請點擊這裡。

前往套件管理器主控台。 輸入以下命令然後按下 Enter 鍵。

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
$vbLabelText   $csharpLabel

try-catch 用於捕捉任何執行期異常。

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

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

AddBarcodeValueTextAboveBarcode 函數將添加條碼值。 IronBarcode 提供其他的條碼設定,例如 max-heightmax-widthbarcodecolor 等。 您可以探索並利用各種參數。

SaveAsJpeg 函數将路徑作為參數並將生成的條形碼保存在該特定路徑。

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

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

透過將編碼方案從Code128更改為QRCode,也可以以相同的方式生成QR碼。

新增視圖

下一步是通過添加一個新的 View 來為這個 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")
}
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
$vbLabelText   $csharpLabel

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

輸出

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

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

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

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

輸入您的條碼內容

點擊建立按鈕。 條碼影像將會被生成並如下面所示顯示在螢幕上。

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

從 URL 生成條碼

摘要

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

還有許多其他有用的庫,例如用於處理 PDF 文檔的 IronPDF,用於處理 Excel 文檔的 IronXL,以及用於處理 OCR 的 IronOCR。 目前,您可以通過購買完整的Iron Suite,以兩個的價格獲得全部五個庫。請訪問我們的授權頁面以獲取更多詳情。

喬迪·巴迪亞
軟體工程師
Jordi 最擅長 Python、C# 和 C++,當他不在 Iron Software 發揮技能時,他會進行遊戲編程。他負責產品測試、產品開發和研究,為持續產品改進增添了巨大的價值。多樣化的經驗使他感到挑戰和投入,他說這是與 Iron Software 合作的最喜歡的方面之一。Jordi 在佛羅里達州邁阿密長大,並在佛羅里達大學學習計算機科學和統計學。
< 上一頁
如何在 C# Windows 應用程式中生成 QR 碼
下一個 >
條碼生成器 .NET 教程