如何在ASP.NET C#中打印條碼
本文將示範如何使用 C# 在 ASP.NET Web 應用程式中列印條碼影像。 本範例將使用 MVC 框架,但您也可以根據需要使用 ASP.NET Web Forms、Windows Forms 或 Web API。
對 ASP.NET MVC 框架有基本的了解將有助於您更好地理解本文。
- 安裝 C# 庫以列印條碼文件
- 配置模型和控制器
- 在 C# 中使用
CreateBarcode方法建立條碼 - 配置視圖以顯示生成的條碼
- 使用打印機或列印到PDF軟體列印包含條碼影像的網頁
建立一個 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; }
}
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
將使用 FileName 從使用者取得條碼圖片名稱。 BarcodeContent 用於取得條碼的內容。
新增控制器
接下來,向項目中新增 Controller。 它將使用 MVC 模型與 View 和 Model 進行通訊。 產生條碼的程式碼僅由兩三行組成。 因此,沒有必要單獨設立一個類別; 相反,代碼被添加到控制器內部。
若要新增控制器,請右鍵點選"控制器"資料夾 >新增>控制器。 將出現一個新視窗。 選擇 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();
}
}
}
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
try-catch用於捕獲任何運行時異常。- 由
BarcodeWriter類別提供的CreateBarcode函數接受兩個參數:條碼內容和編碼方案。 此外,它還接受 11 個其他可選參數,包括最大高度、最大寬度等等。 Server.MapPath函數用於對應產生的條碼影像的儲存路徑。Path.Combine方法會將路徑和條碼圖像名稱組合在一起。AddBarcodeValueTextAboveBarcode函數將會新增條碼值。 IronBarcode 也提供其他條碼設置,例如max-height、max-width、barcode、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")
}
接下來,在視圖中按一下滑鼠右鍵,然後按一下"執行到瀏覽器"按鈕。
輸出
如何在 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 套裝,即可享受僅需兩個庫的價格獲得全部五個庫。請造訪我們的授權頁面以了解更多詳情。
常見問題解答
如何在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。這些庫提供了全面的文件管理解決方案。

