How to Print Barcode in ASP.NET in C#
本文将演示如何在ASP.NET Web应用程序中使用C#打印条形码图像。 在这个示例中将使用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项目
添加模型
右键点击Models文件夹 > 添加 > 类...。
导航至添加类对话框
将出现一个新窗口。 将类命名为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 ClassFileName将用于从用户处获取条形码图像名称。 BarcodeContent用于获取条形码的内容。
添加控制器
接下来,将为项目添加一个Controller。 它将通过MVC模型与View和Model通信。 生成条形码的代码仅由两到三行组成。 因此,不需要单独的类; 而是将代码添加到控制器中。
要添加控制器,右键点击Controllers文件夹 > 添加 > 控制器。 将出现一个新窗口。 选择空的MVC 5控制器。 点击添加按钮。 一个新框将出现。
添加控制器对话框
编写您的控制器名称,例如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,也可以生成QR码。
添加视图
下一步是通过添加新视图为此ASP.NET Web应用程序提供客户端界面。 右键点击控制器方法的名称并单击"添加视图"按钮。
导航至添加视图对话框
将出现一个新窗口。 选择MVC 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")
}接下来,右键点击视图内部,并点击运行到浏览器按钮。
输出
运行Web应用程序以显示创建表单
输入您的条形码图像名称和条形码内容,如下所示:
输入您的条形码内容
点击创建按钮。 条形码图像将被生成并显示在屏幕上,如下所示。
从URL生成条形码
摘要
本教程演示了如何结合使用MVC框架在ASP.NET中用C#生成条形码。 Microsoft Visual Studio被用作IDE。IronPDF是免费的第三方库,兼容所有.NET Framework版本,包括新发布的版本。 IronBarcode速度快,并为处理条形码提供多种功能。 它还可以通过指定不同类型生成QR码。
还有许多其他实用库,如用于处理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,安装 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。这些库为文档管理任务提供全面的解决方案。







