跳過到頁腳內容
使用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也提供其他條碼設置,例如 color 等等。 您可以探索和利用各種參數。
  • 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 是一個第三方IronPDF,可免費用於開發,並且相容於所有版本的.NET Framework,包括最新發布的版本。 IronBarcode速度快,並提供多種條碼處理功能。 它還可以透過指定不同類型的二維碼來產生二維碼

還有許多其他有用的程式庫,例如用於處理 PDF 文件的IronPDF 、用於處理 Excel 文件的IronXL和用於處理 OCR 的IronOCR 。 現在購買完整的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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me