ASP.NETでバーコードを印刷する方法
この記事では、C#を使用してASP.NET Webアプリケーションでバーコード画像を印刷する方法を示します。 この例ではMVCフレームワークが使用されますが、ニーズに応じてASP.NET Webフォーム、Windowsフォーム、または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はバーコードのコンテンツを取るために使用されます。
コントローラーを追加する
次にプロジェクトにコントローラーを追加します。 MVCモデルを使用してビューおよびモデルと通信します。 バーコードを生成するコードは2、3行程度で構成されています。 したがって、別クラスは必要ありません; 代わりに、コントローラー内にコードを追加します。
コントローラーを追加するには、Controllersフォルダを右クリック > 追加 > コントローラー 新しいウィンドウが表示されます。 MVC 5 コントローラー 空を選択します。 追加ボタンをクリック。 新しいボックスが表示されます。
コントローラーダイアログを追加
コントローラー名を例としてBarcodeControllerと書きます。 追加ボタンをクリックしてください。 新しいコントローラーが生成されます。
次のステップはバーコードライブラリをインストールすることです。
バーコードライブラリをインストールする
IronBarcodeライブラリは、バーコードを生成するためのサードパーティライブラリとして推奨されます。 [25] 開発には無料で提供され、バーコードをカスタマイズするための複数の機能を提供します。たとえば、バーコード画像にロゴを追加したり、バーコードの上または下に値を追加したり、バーコードの上または下に注釈を追加したり、バーコードのサイズを変更したり、複数の画像フォーマットでバーコードを保存することができます。詳細については、こちらをクリックしてください。
パッケージマネージャーコンソールに移動します。 以下のコマンドを入力し、Enterを押します。
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 Classtry-catchはランタイム例外をキャッチするために使用されます。BarcodeWriterクラスが提供するCreateBarcode関数は、バーコードコンテンツとエンコードスキームの2つの引数を取ります。 さらに、最大高さ、最大幅など11の他のオプション引数も受け入れます。Server.MapPath関数は生成されたバーコード画像が保存されるパスをマッピングするために使用されます。Path.Combineメソッドはパスとバーコード画像名を結合します。AddBarcodeValueTextAboveBarcode関数はバーコードの値を追加します。 IronBarcodeはmax-height、max-width、barcode、colorなどの他のバーコード設定を提供します。 様々なパラメータを探して使用することができます。SaveAsJpeg関数はパスを引数として取り、その特定のパスに生成されたバーコードを保存します。Directory.GetFilesメソッドは新たに生成されたバーコード画像を取得します。ViewBag.FileNameは生成されたバーコード画像を表示するためのビューにバーコード画像のパスを送信するために使用されます。
QRコードも同様にエンコードスキームをCode128からQRCodeに変更することで生成できます。
ビューを追加する
次のステップは新しいビューを追加して、この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を購入することで、全5ライブラリを2つの料金で手に入れることができます。詳細についてはライセンスページをご覧ください。
よくある質問
ASP.NET MVCでC#を使用してバーコード画像を生成および印刷するにはどうすればよいですか?
ASP.NET MVCアプリケーションでバーコード画像を生成および印刷するには、IronBarcodeライブラリを使用できます。これには、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などのライブラリを提供しています。これらのライブラリは、ドキュメント管理タスクに対する包括的なソリューションを提供します。






