IRONBARCODEの使用

ASP.NETでバーコードを印刷する方法 (C#)

ジョルディ・バルディア
ジョルディ・バルディア
2022年6月25日
更新済み 2024年1月20日
共有:

この記事では、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でバーコードを印刷する方法 in C#, 図1: 新しいASP.NETプロジェクトを作成

新しいASP.NETプロジェクトを作成する

モデルを追加

モデルフォルダーを右クリック > 追加 > クラス...

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と通信します。 バーコードを生成するコードは、わずか2~3行で構成されています。 したがって、別のクラスは必要ありません。 代わりに、コードはコントローラーの中に追加されます。

コントローラーを追加するには、Controllersフォルダーを右クリックし、追加 > コントローラーを選択します。 新しいウィンドウが表示されます。 MVC 5 コントローラーを選択して、空にする。 追加 ボタンをクリックします。 新しいボックスが表示されます。

ASP.NETでバーコードを印刷する方法 C#、図3: コントローラ追加ダイアログ

コントローラー追加ダイアログ

コントローラ名を入力します。例えば、BarcodeController。 「追加」ボタンをクリックします。 新しいコントローラーが生成されます。

次のステップは、バーコードライブラリをインストールすることです。

バーコードライブラリのインストール

IronBarcodeライブラリはバーコード生成のためのサードパーティライブラリとして推奨されます。 開発用は無料であり、バーコードのカスタマイズに複数の機能を提供します。例えば、バーコード画像にロゴを追加する、バーコードの下または上に値を追加する、バーコードの下または上に注釈を追加する、バーコードをリサイズする、バーコードを複数の画像フォーマットで保存する、などがあります。詳しくは、こちらをクリックしてください。

パッケージ マネージャー コンソールに移動します。 次のコマンドを入力し、Enterキーを押してください。

Install-Package BarCode

このコマンドはプロジェクトにIronBarcodeライブラリをインストールします。

バーコードを生成する

次に、次のサンプルコードをコントローラーに追加してください。

[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 は、ランタイム例外をキャッチするために使用されます。

BarcodeWriter クラスによって提供される CreateBarcode 関数は、2つの引数を取ります: バーコードの内容とエンコーディングスキーム。 さらに、最大高さ、最大幅などを含む11の他のオプション引数も受け付けます。

Server.MapPath 関数は、生成されたバーコード画像を保存するパスをマッピングするために使用されます。 Path.Combine メソッドは、パスとバーコード画像名を結合します。

AddBarcodeValueTextAboveBarcode 関数はバーコードの値を追加します。 IronBarcodeは、max-heightmax-widthbarcodecolorなどの他のバーコード設定を提供します。 さまざまなパラメータを探索して利用することができます。

SaveAsJpeg 関数はパスを引数として受け取り、その特定のパスに生成されたバーコードを保存します。

Directory.GetFile メソッドは、新しく生成されたバーコード画像を取得します。

ViewBag.FileName は、生成されたバーコード画像を表示するためにバーコード画像のパスをビューに送信するために使用されます。

QRコードは、エンコーディング方式をCode128からQRCodeに変更することで同様に生成できます。

表示を追加

次のステップは、新しいビューを追加して、このASP.NET Webアプリケーションのクライアント側を提供することです。 コントローラーメソッドの名前を右クリックし、「Add View」ボタンをクリックします。

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

次に、ビュー内を右クリックし、Run to Browserボタンをクリックします。

出力

ASP.NETでバーコードを印刷する方法、図6: Webアプリケーションを実行して作成フォームを表示

Webアプリケーションを実行して作成フォームを表示

バーコード画像の名前とバーコード内容を以下に示すように入力してください:

ASP.NETでバーコードをC#で印刷する方法、図7: バーコードの内容を入力します

バーコードコンテンツを入力してください

Create ボタンをクリックします。 バーコード画像は、以下に示すようにスクリーンに生成され表示されます。

ASP.NETでのバーコードの印刷方法 C#でのASP.NETにおけるバーコードの印刷、図8:URLからバーコードを生成

URLからバーコードを生成する

サマリー

このチュートリアルでは、MVCフレームワークと組み合わせたC#のASP.NETを使用してバーコードを生成する方法を示しました。 Microsoft Visual StudioはIDEとして使用されます。IronPDFはサードパーティライブラリであり、開発のために無料で提供されており、新しくリリースされたバージョンを含むすべての.NET Frameworkのバージョンと互換性があります。 IronBarcodeは高速で、バーコードを扱うための様々な機能を提供します。 異なるタイプを指定することによってQRコードを生成することもできます。

PDFドキュメントの操作に使用するIronPDF、Excelドキュメントの操作に使用するIronXL、OCRの操作に使用するIronOCRなど、他にも多くの便利なライブラリがあります。 現在、Iron Suiteを購入すると、5つのライブラリすべてを2つのライブラリの価格で入手できます。詳細については、ライセンスページをご覧ください。

ジョルディ・バルディア
ソフトウェアエンジニア
ジョルディは、Iron Softwareでのスキルを活かしていないときには、ゲームプログラミングをしており、Python、C#、C++に最も堪能です。彼は製品テスト、製品開発、研究の責任を共有しており、継続的な製品改善に大きな価値をもたらしています。この多様な経験は彼を常に挑戦的で魅力的に保ち、彼はIron Softwareで働く一番好きな側面の一つだと言っています。ジョルディはフロリダ州マイアミで育ち、フロリダ大学でコンピューターサイエンスと統計学を学びました。
< 以前
C# WindowsアプリケーションでQRコードを生成する方法
次へ >
バーコードジェネレーター .NET チュートリアル