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

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

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

掌握 ASP.NET MVC 框架的基本知識將使您更好地理解本文。

class="hsg-featured-snippet"> ## 如何在 C# 中列印條碼文件
  1. 安裝 C# 庫以列印條碼文件
  2. 配置模型和控制器
  3. 使用 CreateBarcode 方法在 C# 中創建條碼
  4. 配置視圖以顯示生成的條碼
  5. 使用打印機或打印到 PDF 軟體列印包含條碼圖像的網頁

創建 MVC 專案

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

如何在 ASP.NET 中以 C# 列印條碼,圖 1:創建新 ASP.NET 專案 創建新 ASP.NET 專案

新增模型

右鍵單擊 Models 資料夾 > 新增 > 類別...

如何在 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 模型與視圖(View)和模型(Model)進行通信。 生成條碼的代碼僅由兩三行代碼組成。 因此,無需單獨的類別; 相反,代碼直接添加在控制器中。

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

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

撰寫您的控制器名稱,例如 BarcodeController。 點擊新增按鈕。 將生成一個新的控制器。

下一步是安裝條碼庫。

安裝條碼庫

推薦使用 IronBarcode 庫作為生成條碼的第三方庫。 It is free for development and provides multiple features to customize barcodes, such as adding a logo to a barcode image, adding value below or above the barcode, adding annotations below or above the barcode, resizing the barcode, saving the barcode in multiple image formats, etc. For more details, please click here.

轉到 套件管理器控制台。 輸入以下命令並按 Enter。

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 同樣生成 QR 碼。

新增視圖

接下來的步驟是通過新增新的視圖為這個 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

接下來,右鍵點擊視圖內部,並點擊 Run to Browser 按鈕。

輸出

如何在 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 快速且提供多種用於處理條碼的功能。 它還可以通過指定不同類型生成 QR 碼

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

常見問題解答

如何在ASP.NET MVC中使用C#生成和列印條碼影像?

您可以使用IronBarcode庫在ASP.NET MVC應用程序中生成並列印條碼影像。這涉及到創建一個MVC項目,通過包管理器控制台安裝IronBarcode,並使用`BarcodeWriter.CreateBarcode`方法生成條碼。

創建新的MVC項目以列印條碼需要哪些步驟?

要創建新的MVC項目以列印條碼,請打開Microsoft Visual Studio,選擇「創建新項目」,選擇「ASP.NET Web應用程序」,然後從可用的模板中選擇「MVC」。

如何在C#中安裝IronBarcode庫以生成條碼?

通過在Visual Studio中打開包管理器控制台並執行命令:Install-Package IronBarcode,來安裝IronBarcode庫。

如何在C#中保存生成的條碼影像?

您可以使用IronBarcode提供的`SaveAsJpeg`方法指定影像保存的文件路徑來保存生成的條碼影像。

我可以在ASP.NET應用程序中自訂條碼影像嗎?

可以,IronBarcode允許自訂條碼影像,包括添加標誌、註釋以及更改大小和尺寸以滿足您的需求。

如何在MVC視圖中顯示生成的條碼?

要在MVC視圖中顯示生成的條碼,請在您的項目中創建一個視圖,並使用`ViewBag`將條碼影像的路徑傳遞給視圖,以便在客戶端顯示條碼。

如果在條碼生成過程中遇到錯誤,我應該怎麼做?

在您的C#代碼中使用try-catch塊來處理條碼生成過程中可能出現的任何運行時異常,以確保強大的錯誤處理。

是否可以使用與條碼相同的方法生成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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。