使用IRONBARCODE

如何在ASP.NET中使用C#打印条形码

Kannaopat Udonpant
坎那帕·乌东攀
2022年六月25日
更新 2024年一月20日
分享:

本文将演示如何在 ASP.NET Web 应用程序中使用 C# 打印条形码图像。 本例将使用 MVC Framework,但您也可以根据需要使用 ASP.NET Web Forms、Windows Forms 或 Web API。

掌握 ASP.NET MVC Framework 的基本知识可以让您更好地理解本文。


创建 MVC 项目

打开 Microsoft Visual Studio。 点击 创建新项目 > 从模板中选择 ASP.NET Web 应用程序 > 按 下一步 > 命名您的项目 > 按 下一步 > 选择 MVC > 点击 创建 按钮。 项目创建如下所示。

如何在 ASP.NET 中使用 C# 打印条码,图1:创建一个新的 ASP.NET 项目

创建一个新的ASP.NET项目

添加模型

右键点击 Models 文件夹 > 添加 > 类...

如何在 ASP.NET 中使用 C# 打印条形码,图 2:导航到添加类对话框

导航到添加类对话框

一个新窗口将会出现。 将您的类命名为BarcodeModel

在模型类中编写以下代码。

public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string FileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
public class BarcodeModel
{
    [Display(Name ="Barcode File Name")]
    public string FileName { get; set; }

    [Display(Name = "Barcode Content")]
    public string BarcodeContent { get; set; }
}
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模型与ViewModel进行通信。 生成 BarCode 的代码只有两三行。 因此,没有必要单独开班; 在翻译过程中,我们会在 Controller 中添加代码。

要添加控制器,请右键单击 Controllers 文件夹 > 添加 > 控制器。 一个新窗口将会出现。 选择 MVC 5 Controller Empty。 点击添加按钮。 将出现一个新框。

如何在 ASP.NET 中使用 C# 打印条形码, 图 3: 添加控制器对话框

添加控制器对话框

编写您的控制器名称,例如BarcodeController。 单击添加按钮。 将生成一个新的控制器。

下一步是安装 BarCode 库。

安装 BarCode 库

推荐使用 IronBarcode 库作为生成条形码的第三方库。 它是免费的开发工具,提供多种功能来自定义条形码,例如在条形码图像中添加徽标、在条形码的上方或下方添加值、在条形码的上方或下方添加注释、调整条形码大小、将条形码保存为多种图像格式等。有关详细信息,请点击此处。

转到软件包管理器控制台。 键入以下命令并按 Enter。

Install-Package BarCode

该命令将在项目中安装 IronBarcode 库。

生成 BarCode

接下来,在控制器中添加以下示例代码。

[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path, model.FileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
[HttpPost]
public ActionResult CreateBarcode(BarcodeModel model)
{
    try
    {
        var MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128);
        string path = Server.MapPath("~/Files/");
        string filepath = Path.Combine(path, model.FileName);
        MyBarCode.AddBarcodeValueTextAboveBarcode();
        MyBarCode.SaveAsJpeg(filepath);
        string image = Directory.GetFiles(path).FirstOrDefault();
        ViewBag.fileName = image;
        return View();
    }
    catch
    {
        return View();
    }
}
<HttpPost>
Public Function CreateBarcode(ByVal model As BarcodeModel) As ActionResult
	Try
		Dim MyBarCode = IronBarCode.BarcodeWriter.CreateBarcode(model.BarcodeContent, BarcodeEncoding.Code128)
		Dim path As String = Server.MapPath("~/Files/")
		Dim filepath As String = System.IO.Path.Combine(path, model.FileName)
		MyBarCode.AddBarcodeValueTextAboveBarcode()
		MyBarCode.SaveAsJpeg(filepath)
		Dim image As String = Directory.GetFiles(path).FirstOrDefault()
		ViewBag.fileName = image
		Return View()
	Catch
		Return View()
	End Try
End Function
$vbLabelText   $csharpLabel

try-catch用于捕获任何运行时异常。

CreateBarcode 函数由 BarcodeWriter 类提供,接受两个参数:条码内容和编码方案。 此外,它还接受 11 个其他可选参数,包括最大高度、最大宽度等。

Server.MapPath 函数用于映射生成的条形码图像保存的路径。 Path.Combine 方法将组合路径和条形码图像名称。

AddBarcodeValueTextAboveBarcode 函数将添加条形码值。 IronBarcode提供了其他条码设置,如max-heightmax-widthbarcodecolor等等。 您可以探索并使用各种参数。

SaveAsJpeg 函数将路径作为参数,并在该特定路径中保存生成的条形码。

Directory.GetFile 方法将获取新生成的条形码图像。

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")
}
model ReadOnly Property () As GenerateBarcodeMVC.Models.BarcodeModel
ViewBag.DisplayBarcode = False
End Property

'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Create</h2> [using](Html.BeginForm())
If True Then
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
Html.AntiForgeryToken() <div class="form-horizontal"> (Of h4) GenerateBarcode</h4> <hr /> Html.ValidationSummary(True, "", New With {Key .class = "text-danger"}) <div class="form-group"> Html.LabelFor(Function(model) model.FileName, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.FileName, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.FileName, "", New With {Key .class = "text-danger"}) </div> </div> <div class="form-group"> Html.LabelFor(Function(model) model.BarcodeContent, htmlAttributes:= New With {Key .class = "control-label col-md-2"}) <div class="col-md-10"> Html.EditorFor(Function(model) model.BarcodeContent, New With {
	Key .htmlAttributes = New With {Key .class = "form-control"}
}) Html.ValidationMessageFor(Function(model) model.BarcodeContent, "", New With {Key .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>
End If
Dim Scripts As section
If True Then
Scripts.Render("~/bundles/jqueryval")
End If
$vbLabelText   $csharpLabel

接下来,右键单击视图,然后单击 "运行到浏览器 "按钮。

输出

如何在 ASP.NET 中使用 C# 打印条形码,图 6:运行 Web 应用程序以显示创建表单

运行网页应用程序以显示创建表单

如下所示,输入您的条形码图像名称和条形码内容:

如何在ASP.NET的C#中打印条形码,图7:输入你的条形码内容

输入您的条形码内容

点击创建按钮。 条形码图像将生成并显示在屏幕上,如下图所示。

如何在 ASP.NET 中使用 C# 打印条形码,图 8:从 URL 生成条形码

从URL生成条形码

摘要

本教程演示了如何使用 C# 中的 ASP.NET 并结合 MVC Framework 生成条形码。 Microsoft Visual Studio 被用作集成开发环境。IronPDF 是一个第三方库,可免费用于开发,兼容所有版本的 .NET Framework,包括最新发布的版本。 IronBarcode 运行速度快,提供多种处理条形码的功能。 它还可以通过指定不同类型来生成二维码

还有其他许多有用的库,如处理 PDF 文档的 IronPDF、处理 Excel 文档的 IronXL 和处理 OCR 的 IronOCR。 目前,您可以通过购买完整的Iron Suite以仅仅两套的价格获得全部五个库。请访问我们的许可页面了解更多详情。

Kannaopat Udonpant
坎那帕·乌东攀
软件工程师
在成为软件工程师之前,Kannapat 从日本北海道大学完成了环境资源博士学位。在攻读学位期间,Kannapat 还成为了生物生产工程系车辆机器人实验室的成员。2022年,他利用自己的 C# 技能加入了 Iron Software 的工程团队,专注于 IronPDF。Kannapat 珍视他的工作,因为他能直接向编写 IronPDF 大部分代码的开发者学习。除了同伴学习,Kannapat 还享受在 Iron Software 工作的社交方面。不写代码或文档时,Kannapat 通常在 PS5 上玩游戏或重看《最后生还者》。
< 前一页
如何在C# Windows应用程序中生成二维码
下一步 >
条形码生成器 .NET 教程