跳至頁尾內容
使用 IRONBARCODE
如何在 ASP.NET 中列印條碼

如何在 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; }
}
$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();
        }
    }
}
$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 套裝,即可享受僅需兩個庫的價格獲得全部五個庫。請造訪我們的授權頁面以了解更多詳情。

常見問題解答

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

您可以使用 IronBarcode 庫在 ASP.NET MVC 應用程式中產生和列印條碼圖像。這包括建立一個 MVC 項目,透過程式包管理器控制台安裝 IronBarcode,然後使用 `BarcodeWriter.CreateBarcode` 方法產生條碼。

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

若要建立一個用於條碼列印的新 MVC 項目,請開啟 Microsoft Visual Studio,選擇“建立新專案”,選擇“ASP.NET Web 應用程式”,然後從可用範本中選擇“MVC”。

如何在 C# 中安裝用於條碼產生的 IronBarcode 庫?

在 Visual Studio 中開啟程式包管理器控制台,然後執行命令來安裝Install-Package IronBarcode Package IronBarcode 。

如何在C#中儲存產生的條碼影像?

您可以使用 IronBarcode 提供的 `SaveAsJpeg` 方法儲存產生的條碼影像,並指定影像應儲存的檔案路徑。

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

是的,IronBarcode 允許自訂條碼圖像,包括添加徽標、註釋以及更改尺寸和規格以滿足您的需求。

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

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

條碼產生過程中如果遇到錯誤該怎麼辦?

在 C# 程式碼中使用 try-catch 區塊來處理條碼產生過程中可能發生的任何執行時間異常,從而確保強大的錯誤處理能力。

是否可以使用與產生條碼相同的方法產生二維碼?

是的,使用 IronBarcode,您可以透過在 `BarcodeWriter.CreateBarcode` 方法中將編碼方案設為 `QRCode` 來產生二維碼。

除了 Iron 軟體庫之外,還有哪些推薦的文件管理庫?

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

柯蒂斯·週
技術撰稿人

Curtis Chau擁有卡爾頓大學電腦科學學士學位,專長於前端開發,精通Node.js、TypeScript、JavaScript和React。他熱衷於打造直覺美觀的使用者介面,喜歡使用現代框架,並擅長撰寫結構清晰、視覺效果出色的使用者手冊。

除了開發工作之外,柯蒂斯對物聯網 (IoT) 也抱有濃厚的興趣,致力於探索硬體和軟體整合的創新方法。閒暇時,他喜歡玩遊戲和製作 Discord 機器人,將他對科技的熱愛與創造力結合。