.NET ヘルプ

.NETソフトウェア開発(開発者向けの仕組み)

更新済み 3月 26, 2024
共有:

.NET Frameworkソフトウェア開発 は、Microsoft によってサポートされている強力で多用途なフレームワークであり、.NET 開発者がさまざまなプラットフォーム、オペレーティングシステム、およびデバイスにわたって堅牢で高品質なアプリケーションを作成できるようにします。 このソフトウェア開発フレームワークは総合的に設計されており、ソフトウェア開発者が.NETプラットフォームで効率的にWeb、デスクトップ、およびモバイルアプリケーションを構築するために使用できるツール、ライブラリ、およびAPIを提供します。

複数のプログラミング言語、C#、Visual Basic、F#を含むサポートにより、.NET開発は開発者が好みの言語で作業できるようにしながら、.NET Coreエコシステムの豊富な機能の恩恵を受けられるようにその柔軟性を拡張します。 このチュートリアルでは、見てみましょう IronPDF 実際の問題を解決するための.NET開発を実演するためのアクション。

.NETソフトウェア開発のエコシステムを理解する

.NETエコシステムは、主要な.NET実装であり、異なるオペレーティングシステム間でのアプリケーション開発を容易にするために設計されたさまざまなコンポーネントと技術を含む幅広いプラットフォームです。 本質的に、.NET Framework と .NET Core は、.NET アプリケーションを実行するための主要なエンジンとして機能し、共通言語ランタイムを提供します。 (CLR (共通言語ランタイム)) コードの実行を管理し、メモリ管理、型安全性、例外処理などのサービスを提供します。

共通言語ランタイム (CLR (共通言語ランタイム))

CLRは.NETアーキテクチャの重要な要素であり、異なるオペレーティングシステム上で.NETコードを実行することを可能にします。 共通中間言語をコンパイルします。 (CIL) ホストマシンが直接実行できるネイティブ機械コードに変換します。 このプロセスにより、.NETアプリケーションは主要なモバイルオペレーティングシステムからWindowsウェブサーバーまで、さまざまなプラットフォームでシームレスに実行できることが保証されます。

クロスプラットフォームフレームワーク

.NET Coreはクロスプラットフォームフレームワークとして登場し、.NETアプリケーションをLinux、macOS、およびWindows上で実行することを可能にします。 この適応性により、.NETは、さまざまなデバイスやプラットフォームでより広いオーディエンスにリーチしようとする開発者にとって魅力的な選択肢となります。 .NET Coreを使用すると、アプリケーションはサポートされている任意のオペレーティングシステムで開発および展開でき、.NETソフトウェア開発の範囲と柔軟性が向上します。これにより、広範な.NETコミュニティによって強化されます。

統合開発環境 (IDE (統合開発環境))

Visual Studioは、優れた統合開発環境として際立っています (IDE (統合開発環境)) .NET開発用。 それは開発者にコードの記述、デバッグ、および.NETアプリケーションの展開のための強力なツールを提供します。 Visual Studioは、さまざまなプログラミング言語をサポートし、Web、デスクトップ、およびモバイルアプリケーションを構築するための豊富な機能を提供するため、.NET開発者にとって欠かせないツールです。

.NET を使用したアプリケーションの構築

.NETプラットフォームでアプリケーションを作成するには、フレームワークが提供する多岐にわたるツール、ライブラリ、およびプログラミング言語(例えば、Visual Basicなど)を活用する必要があり、その包括的なエコシステムを示しています。 この多様性により、ソフトウェア開発者は、Webおよびデスクトップアプリケーションからクラウドベースおよびモバイルソリューションに至るまで、さまざまなタイプの.NETアプリケーションを構築することができます。

ASP.NETによるWeb開発

ASP.NETは、.NETフレームワークの重要な部分であり、動的なウェブページやアプリケーションを構築するために特別に設計されています。 それにより、開発者は大量のトラフィックを処理できる応答性が高くスケーラブルなWebアプリケーションを作成することができます。 ASP.NET Core は、ASP.NET のオープンソース版であり、クロスプラットフォームの Web アプリケーションを構築するための追加機能を提供します。これにより、Windows、Linux、および macOS 上で Web アプリを開発および展開することが可能になります。

デスクトップアプリケーション開発

.NETはデスクトップアプリケーションを作成するために、主に2つのアプローチを提供しています:Windows FormsとWindows Presentation Foundation (WPF). Windows Formsは、リッチなグラフィカルユーザーインターフェースを持つデスクトップアプリを簡単に作成する方法を提供します。一方、WPFはXAMLを使用します。 (拡張可能アプリケーションマークアップ言語) 高度なグラフィックスとアニメーションを備えた視覚的に魅力的なユーザーインターフェイスの開発を可能にするため。

モバイルアプリケーション開発

モバイル開発向けに、.NETは主なモバイルオペレーティングシステムに対するサポートをXamarinフレームワークを通じて提供し、現在では.NET MAUIとして.NETに統合されています。 (マルチプラットフォームアプリUI). このアプローチにより、開発者はiOS、Android、およびWindows全体でコードを再利用できるため、ネイティブのパフォーマンスとユーザーエクスペリエンスを提供するモバイルアプリケーションの作成プロセスが簡素化されます。

クラウドとマイクロサービス

.NETはクラウド上で動作するアプリケーションの開発にも適しています。 Azureやその他のクラウドプラットフォームのサポートにより、開発者はクラウドコンピューティングリソースを活用したスケーラブルで分散型のアプリケーションを構築できます。 ASP.NET Coreは、クラウド環境内でスケールできる軽量でモジュール化され、独立してデプロイ可能なサービスを提供することで、マイクロサービスの開発において重要な役割を果たします。

機械学習と人工知能

.NETエコシステムには、開発者がカスタム機械学習モデルを.NETアプリケーションに組み込むことを可能にする機械学習フレームワークであるML.NETが含まれています。 この統合により、.NETフレームワーク内でAIの力を活用し、予測分析、自然言語処理などのインテリジェントアプリケーションを作成する可能性が広がります。

IronPDFで.NETソフトウェア開発を強化

.NETソフトウェア開発(開発者向けの動作方法):図1 - IronPDF

.NETソフトウェア開発の活気あるエコシステム内で、アプリケーション内で直接PDF文書を生成、操作、管理する能力は大きな利点を提供します。 IronPDFは、.NET開発者向けに設計された強力なライブラリであり、この環境にシームレスに統合され、Windows Formsで構築されたアプリケーションを含む.NETアプリケーションからPDFを作成する効率的な方法を提供します。

.NETアプリケーションにおけるIronPDFの役割

IronPDFは、.NETエコシステムの柔軟性とパワーの証として、開発者に直感的なAPIを提供します。 HTMLからPDFドキュメントを生成する L、画像、テキスト、そしてASP.NETウェブページまでも。 この機能は、デスクトップアプリケーションで請求書、レポート、個別の文書を生成するなど、動的なドキュメント作成が必要なシナリオで特に有用です。

IronPDFを使用したWindowsフォーム請求書ジェネレーターの作成

請求書を生成するためのWindowsフォームアプリケーションは、.NETソフトウェア開発とIronPDFを組み合わせた実践的なアプリケーションの好例です。 このアプリケーションでは、ユーザーが顧客情報、購入商品、価格などの詳細を入力し、ワンクリックでプロフェッショナルなPDF請求書を生成することができます。

Windows Forms プロジェクトの設定と UI の設計

Visual Studioで新しいWindows Formsプロジェクトを作成することから始めます。 これは、請求書生成ツールのユーザーインターフェースを作成するための基盤です。 顧客および商品情報の入力フィールドを含むフォームを設計し、PDFを生成するためのボタンも配置してください。 これは私たちの請求書生成UIです:

.NETソフトウェア開発(開発者向けの仕組み):図2 - 請求書生成Windowsフォーム出力

Windows Forms アプリケーションのユーザーインターフェースは、使いやすさと機能性を確保するために細心の注意を払って設計されています。 メインウィンドウ「Invoice Generator」は、シームレスなユーザーエクスペリエンスのために異なるセクションに分かれています。

顧客情報セクション

このフォームの上部には、「Customer Name」(顧客名)、「Customer Address」(顧客住所)、「Customer Email」(顧客メール)、「Customer Phone Number」(顧客電話番号)のフィールドが含まれています。このエリアは、生成された請求書に顕著に表示される重要な顧客情報を記録するためのものです。

請求書アイテムの追加

顧客情報のすぐ下に「Add Invoice Item」というエリアがあります。ここでは、ユーザーが「Item ID」、「Description」、「Quantity」、「Unit Price」などの個別アイテムの詳細を入力できます。これらのフィールドの隣には、「Add Item」ボタンがあり、ユーザーが入力したアイテムを下の請求書リストに追加することができます。

請求書項目リスト

フォームの中央部には「請求書情報」セクションがあり、入力項目が追加されるごとにそれらが表示される表が表示されます。 表の列には「商品ID」、「説明」、「数量」、「単価」、「合計金額」が含まれており、最後の列は数量と単価に基づいて自動的に計算されます。「日付を選択」というタイトルの日時選択ツールにより、ユーザーは請求書の日付を指定することができ、ドキュメントの特定性が増します。

請求操作

フォームの下部には「合計金額」というラベルが表示され、アイテムが追加または削除されると動的に更新されます。 これは、ユーザーが請求書の総額をリアルタイムで把握できるようにします。 さらに、「Generate Invoice」ボタンはアプリケーションに入力されたデータに基づいて請求書のPDFバージョンを作成するためにIronPDFライブラリを使用させます。

このユーザーインターフェースは機能的であるだけでなく直感的であり、ユーザーが急な学習曲線なしで容易にアプリケーションと対話できるようにします。 これは、データ入力からPDF作成に至るまでの明確で簡単な道筋を提供しながら、請求書作成に必要なすべての情報を収容するように設計されています。

プロジェクトにIronPDFを追加する

プロジェクトの設定が完了したら、次のステップとしてIronPDFを導入します。 これは、Visual Studio に統合された NuGet パッケージ マネージャーである NuGet を通じて行います。これにより、IronPDF をプロジェクトに簡単に追加することができます。 以下のコマンドを記述して実行してください:

Install-Package IronPdf

このコマンドはIronPDFをインストールし、プロジェクトで使用できるようになります。

.NET ソフトウェア開発 (開発者向けの仕組み):図3 - IronPDFのインストール

請求書生成の実装

Windows Formsアプリケーションの中心は、ユーザー入力を処理し、データを構造化された形式に整理し、具体的なドキュメント、つまりPDF形式の請求書を生成する能力です。 機能はアプリケーションのコードベース内の一連の体系的なステップに基づいて構築されています。

データグリッドビューの設定

フォームが初期化されると、アプリケーションは請求書項目が表示されるデータ構造を設定するために SetupDataGridViewColumns を呼び出します。 項目ID、説明、数量、単価、合計価格の列が作成され、合計価格は自動的に計算されるため、読み取り専用のフィールドとなります。 さらに、請求書の内容を管理するために、アイテムを削除するボタン列が追加され、ユーザーのコンテロールが向上します。

private void SetupDataGridViewColumns()
{
    invoiceDataGridView.Columns.Clear(); // Clear existing columns if any
    // Now add the rest of your columns
    invoiceDataGridView.Columns.Add("itemIdColumn", "Item ID");
    invoiceDataGridView.Columns.Add("descriptionColumn", "Description");
    invoiceDataGridView.Columns.Add("quantityColumn", "Quantity");
    invoiceDataGridView.Columns.Add("unitPriceColumn", "Unit Price");
    invoiceDataGridView.Columns.Add("totalPriceColumn", "Total Price");
    // Set the Total Price column to read-only as it will be calculated automatically
    invoiceDataGridView.Columns ["totalPriceColumn"].ReadOnly = true;
    // Add a button column for delete action
    DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
    deleteButtonColumn.HeaderText = "";
    deleteButtonColumn.Name = "deleteButtonColumn";
    deleteButtonColumn.Text = "Delete";
    deleteButtonColumn.UseColumnTextForButtonValue = true; // This will set the button text to "Delete"
    // Add the delete button column to the DataGridView
    invoiceDataGridView.Columns.Add(deleteButtonColumn);
}
public Form1()
{
    InitializeComponent();
    SetupDataGridViewColumns();
    // Wire up the CellClick event to a handler
    invoiceDataGridView.CellClick += invoiceDataGridView_CellClick;
}
private void invoiceDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // If the clicked cell is part of the button column and not the header row
    if (e.ColumnIndex == invoiceDataGridView.Columns ["deleteButtonColumn"].Index && e.RowIndex >= 0)
    {
        // Confirm delete operation
        if (MessageBox.Show("Are you sure you want to delete this item?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            // Remove the row from the DataGridView
            invoiceDataGridView.Rows.RemoveAt(e.RowIndex);
        }
    }
}
private void SetupDataGridViewColumns()
{
    invoiceDataGridView.Columns.Clear(); // Clear existing columns if any
    // Now add the rest of your columns
    invoiceDataGridView.Columns.Add("itemIdColumn", "Item ID");
    invoiceDataGridView.Columns.Add("descriptionColumn", "Description");
    invoiceDataGridView.Columns.Add("quantityColumn", "Quantity");
    invoiceDataGridView.Columns.Add("unitPriceColumn", "Unit Price");
    invoiceDataGridView.Columns.Add("totalPriceColumn", "Total Price");
    // Set the Total Price column to read-only as it will be calculated automatically
    invoiceDataGridView.Columns ["totalPriceColumn"].ReadOnly = true;
    // Add a button column for delete action
    DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
    deleteButtonColumn.HeaderText = "";
    deleteButtonColumn.Name = "deleteButtonColumn";
    deleteButtonColumn.Text = "Delete";
    deleteButtonColumn.UseColumnTextForButtonValue = true; // This will set the button text to "Delete"
    // Add the delete button column to the DataGridView
    invoiceDataGridView.Columns.Add(deleteButtonColumn);
}
public Form1()
{
    InitializeComponent();
    SetupDataGridViewColumns();
    // Wire up the CellClick event to a handler
    invoiceDataGridView.CellClick += invoiceDataGridView_CellClick;
}
private void invoiceDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // If the clicked cell is part of the button column and not the header row
    if (e.ColumnIndex == invoiceDataGridView.Columns ["deleteButtonColumn"].Index && e.RowIndex >= 0)
    {
        // Confirm delete operation
        if (MessageBox.Show("Are you sure you want to delete this item?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            // Remove the row from the DataGridView
            invoiceDataGridView.Rows.RemoveAt(e.RowIndex);
        }
    }
}
Private Sub SetupDataGridViewColumns()
	invoiceDataGridView.Columns.Clear() ' Clear existing columns if any
	' Now add the rest of your columns
	invoiceDataGridView.Columns.Add("itemIdColumn", "Item ID")
	invoiceDataGridView.Columns.Add("descriptionColumn", "Description")
	invoiceDataGridView.Columns.Add("quantityColumn", "Quantity")
	invoiceDataGridView.Columns.Add("unitPriceColumn", "Unit Price")
	invoiceDataGridView.Columns.Add("totalPriceColumn", "Total Price")
	' Set the Total Price column to read-only as it will be calculated automatically
	invoiceDataGridView.Columns ("totalPriceColumn").ReadOnly = True
	' Add a button column for delete action
	Dim deleteButtonColumn As New DataGridViewButtonColumn()
	deleteButtonColumn.HeaderText = ""
	deleteButtonColumn.Name = "deleteButtonColumn"
	deleteButtonColumn.Text = "Delete"
	deleteButtonColumn.UseColumnTextForButtonValue = True ' This will set the button text to "Delete"
	' Add the delete button column to the DataGridView
	invoiceDataGridView.Columns.Add(deleteButtonColumn)
End Sub
'INSTANT VB WARNING: The following constructor is declared outside of its associated class:
'ORIGINAL LINE: public Form1()
Public Sub New()
	InitializeComponent()
	SetupDataGridViewColumns()
	' Wire up the CellClick event to a handler
	AddHandler invoiceDataGridView.CellClick, AddressOf invoiceDataGridView_CellClick
End Sub
Private Sub invoiceDataGridView_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
	' If the clicked cell is part of the button column and not the header row
	If e.ColumnIndex = invoiceDataGridView.Columns ("deleteButtonColumn").Index AndAlso e.RowIndex >= 0 Then
		' Confirm delete operation
		If MessageBox.Show("Are you sure you want to delete this item?", "Confirm Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
			' Remove the row from the DataGridView
			invoiceDataGridView.Rows.RemoveAt(e.RowIndex)
		End If
	End If
End Sub
VB   C#

請求書アイテムの追加

ユーザーがアイテムの詳細を入力して「アイテムを追加」ボタンをクリックすると、btnAddItem_Click イベントが入力データを収集し、それを検証してから AddItemToInvoice を呼び出します。 このメソッドは、入力された値を基に DataGridView に新しい行を追加し、項目の総価格を計算し、フォーム下部に表示される請求書合計金額を更新します。

public void AddItemToInvoice(string itemId, string description, int quantity, decimal unitPrice)
{
    decimal totalPrice = quantity * unitPrice;
    invoiceDataGridView.Rows.Add(itemId, description, quantity, unitPrice, totalPrice);
}
 private void CalculateTotalAmount()
 {
     decimal totalAmount = 0m;
     foreach (DataGridViewRow row in invoiceDataGridView.Rows)
     {
         totalAmount += Convert.ToDecimal(row.Cells ["totalPriceColumn"].Value ?? 0);
     }
     lblTotalAmount.Text = $"{totalAmount:C2}"; // Assuming 'lblTotalAmount' is the name of your Label control
 }
private void btnAddItem_Click(object sender, EventArgs e)
{
    // Assuming your text boxes and numeric up/down controls have the following names:
    // txtItemID, txtDescription, txtUnitPrice, and numericUpDownQuantity
    // Collect data from input controls
    string itemId = txtItemID.Text;
    string description = txtDescription.Text;
    int quantity = (int)numericUpDownQuantity.Value;
    decimal unitPrice;
    // Validate the collected data
    // Check if the unit price is a valid decimal
    bool isUnitPriceValid = decimal.TryParse(txtUnitPrice.Text, out unitPrice);
    // Additional validation can be implemented as needed
    if (string.IsNullOrEmpty(itemId) 
 string.IsNullOrEmpty(description) 
 quantity <= 0 
 !isUnitPriceValid 
 unitPrice <= 0)
    {
        MessageBox.Show("Please enter valid data for all fields.", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
    // Add data to the DataGridView
    AddItemToInvoice(itemId, description, quantity, unitPrice);
    // Optionally, clear the input fields after adding the item to the grid
    txtItemID.Clear();
    txtDescription.Clear();
    txtUnitPrice.Clear();
    numericUpDownQuantity.Value = 0; // or numericUpDownQuantity.Minimum if 0 is not allowed
    CalculateTotalAmount();
}
public void AddItemToInvoice(string itemId, string description, int quantity, decimal unitPrice)
{
    decimal totalPrice = quantity * unitPrice;
    invoiceDataGridView.Rows.Add(itemId, description, quantity, unitPrice, totalPrice);
}
 private void CalculateTotalAmount()
 {
     decimal totalAmount = 0m;
     foreach (DataGridViewRow row in invoiceDataGridView.Rows)
     {
         totalAmount += Convert.ToDecimal(row.Cells ["totalPriceColumn"].Value ?? 0);
     }
     lblTotalAmount.Text = $"{totalAmount:C2}"; // Assuming 'lblTotalAmount' is the name of your Label control
 }
private void btnAddItem_Click(object sender, EventArgs e)
{
    // Assuming your text boxes and numeric up/down controls have the following names:
    // txtItemID, txtDescription, txtUnitPrice, and numericUpDownQuantity
    // Collect data from input controls
    string itemId = txtItemID.Text;
    string description = txtDescription.Text;
    int quantity = (int)numericUpDownQuantity.Value;
    decimal unitPrice;
    // Validate the collected data
    // Check if the unit price is a valid decimal
    bool isUnitPriceValid = decimal.TryParse(txtUnitPrice.Text, out unitPrice);
    // Additional validation can be implemented as needed
    if (string.IsNullOrEmpty(itemId) 
 string.IsNullOrEmpty(description) 
 quantity <= 0 
 !isUnitPriceValid 
 unitPrice <= 0)
    {
        MessageBox.Show("Please enter valid data for all fields.", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        return;
    }
    // Add data to the DataGridView
    AddItemToInvoice(itemId, description, quantity, unitPrice);
    // Optionally, clear the input fields after adding the item to the grid
    txtItemID.Clear();
    txtDescription.Clear();
    txtUnitPrice.Clear();
    numericUpDownQuantity.Value = 0; // or numericUpDownQuantity.Minimum if 0 is not allowed
    CalculateTotalAmount();
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

PDF請求書の生成

「Generate Invoice」をクリックすると、アプリケーションはbtnInvoice_Clickイベントハンドラを実行し、StringBuilderを使用してHTML文字列を構築します。 これは、顧客の詳細とDataGridViewからの請求書アイテムで満たされたスタイル付きHTMLテーブルを含む文字列です。 IronPDFのレンダラーは、このHTMLをPDFドキュメントに変換し、指定されたパスに保存します。 アプリケーションは、ユーザーにメッセージを送信して、請求書の作成が成功したことを確認します。

private void btnInvoice_Click(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Collect customer information
            var customerName = txtName.Text; // Adjusted to your actual TextBox names
            var customerEmail = txtEmail.Text;
            var customerAddress = txtAddress.Text;
            var customerPhone = txtPhone.Text;
            // Start building the HTML content for the invoice
            var htmlStringBuilder = new StringBuilder();
            htmlStringBuilder.Append("<html>");
            htmlStringBuilder.Append("<head>");
            htmlStringBuilder.Append("<title>Invoice</title>");
            // Add some basic CSS styles for the invoice
            htmlStringBuilder.Append(@"
    <style>
        body {
            font-family: 'Arial', sans-serif;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #999;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        h2 {
            text-align: right;
            margin-top: 20px;
        }
.customer-info {
        font-family: 'Helvetica', 'Arial', sans-serif;
        line-height: 1.6;
        margin-bottom: 20px;
    }
    .customer-info p {
        margin: 0 0 10px 0;
        color: #333;
    }
    .customer-info label {
        font-weight: bold;
    }
    </style>");
            // You can add style tags here for styling your PDF content
            htmlStringBuilder.Append("</head>");
            htmlStringBuilder.Append("<body>");
            htmlStringBuilder.Append("<h1>Invoice</h1>");
            htmlStringBuilder.Append("<div class='customer-info'>");
            htmlStringBuilder.Append($"<p><strong>Customer Name:</strong> {customerName}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Email:</strong> {customerEmail}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Address:</strong> {customerAddress}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Phone:</strong> {customerPhone}</p>");
            htmlStringBuilder.Append("</div>");
            // Add the invoice items
            htmlStringBuilder.Append("<table border='1'><tr><th>Item ID</th><th>Description</th><th>Quantity</th><th>Unit Price</th><th>Total Price</th></tr>");
            foreach (DataGridViewRow row in invoiceDataGridView.Rows)
            {
                if (row.IsNewRow) continue; // Skip the new row placeholder
                htmlStringBuilder.Append("<tr>");
                htmlStringBuilder.Append($"<td>{row.Cells ["itemIdColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["descriptionColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["quantityColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["unitPriceColumn"].Value:C2}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["totalPriceColumn"].Value:C2}</td>");
                htmlStringBuilder.Append("</tr>");
            }
            htmlStringBuilder.Append("</table>");
            // Add the total amount
            htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>");
            // Close the HTML string
            htmlStringBuilder.Append("</body></html>");
            // Use IronPDF to convert the HTML string to a PDF document
            var renderer = new IronPdf.ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString());
            // Save the PDF to a file
            string savePath = Path.Combine($"F:\\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf"); // to avoid file name conflicts and save to desktop
            pdfDocument.SaveAs(savePath);
            // Show a success dialog
            MessageBox.Show("The invoice has been successfully saved to your desktop.", "Invoice Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
private void btnInvoice_Click(object sender, EventArgs e)
        {
            IronPdf.License.LicenseKey = "License-Key";
            // Collect customer information
            var customerName = txtName.Text; // Adjusted to your actual TextBox names
            var customerEmail = txtEmail.Text;
            var customerAddress = txtAddress.Text;
            var customerPhone = txtPhone.Text;
            // Start building the HTML content for the invoice
            var htmlStringBuilder = new StringBuilder();
            htmlStringBuilder.Append("<html>");
            htmlStringBuilder.Append("<head>");
            htmlStringBuilder.Append("<title>Invoice</title>");
            // Add some basic CSS styles for the invoice
            htmlStringBuilder.Append(@"
    <style>
        body {
            font-family: 'Arial', sans-serif;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #999;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        h2 {
            text-align: right;
            margin-top: 20px;
        }
.customer-info {
        font-family: 'Helvetica', 'Arial', sans-serif;
        line-height: 1.6;
        margin-bottom: 20px;
    }
    .customer-info p {
        margin: 0 0 10px 0;
        color: #333;
    }
    .customer-info label {
        font-weight: bold;
    }
    </style>");
            // You can add style tags here for styling your PDF content
            htmlStringBuilder.Append("</head>");
            htmlStringBuilder.Append("<body>");
            htmlStringBuilder.Append("<h1>Invoice</h1>");
            htmlStringBuilder.Append("<div class='customer-info'>");
            htmlStringBuilder.Append($"<p><strong>Customer Name:</strong> {customerName}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Email:</strong> {customerEmail}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Address:</strong> {customerAddress}</p>");
            htmlStringBuilder.Append($"<p><strong>Customer Phone:</strong> {customerPhone}</p>");
            htmlStringBuilder.Append("</div>");
            // Add the invoice items
            htmlStringBuilder.Append("<table border='1'><tr><th>Item ID</th><th>Description</th><th>Quantity</th><th>Unit Price</th><th>Total Price</th></tr>");
            foreach (DataGridViewRow row in invoiceDataGridView.Rows)
            {
                if (row.IsNewRow) continue; // Skip the new row placeholder
                htmlStringBuilder.Append("<tr>");
                htmlStringBuilder.Append($"<td>{row.Cells ["itemIdColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["descriptionColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["quantityColumn"].Value}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["unitPriceColumn"].Value:C2}</td>");
                htmlStringBuilder.Append($"<td>{row.Cells ["totalPriceColumn"].Value:C2}</td>");
                htmlStringBuilder.Append("</tr>");
            }
            htmlStringBuilder.Append("</table>");
            // Add the total amount
            htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>");
            // Close the HTML string
            htmlStringBuilder.Append("</body></html>");
            // Use IronPDF to convert the HTML string to a PDF document
            var renderer = new IronPdf.ChromePdfRenderer();
            var pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString());
            // Save the PDF to a file
            string savePath = Path.Combine($"F:\\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf"); // to avoid file name conflicts and save to desktop
            pdfDocument.SaveAs(savePath);
            // Show a success dialog
            MessageBox.Show("The invoice has been successfully saved to your desktop.", "Invoice Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Private Sub btnInvoice_Click(ByVal sender As Object, ByVal e As EventArgs)
			IronPdf.License.LicenseKey = "License-Key"
			' Collect customer information
			Dim customerName = txtName.Text ' Adjusted to your actual TextBox names
			Dim customerEmail = txtEmail.Text
			Dim customerAddress = txtAddress.Text
			Dim customerPhone = txtPhone.Text
			' Start building the HTML content for the invoice
			Dim htmlStringBuilder = New StringBuilder()
			htmlStringBuilder.Append("<html>")
			htmlStringBuilder.Append("<head>")
			htmlStringBuilder.Append("<title>Invoice</title>")
			' Add some basic CSS styles for the invoice
			htmlStringBuilder.Append("
    <style>
        body {
            font-family: 'Arial', sans-serif;
        }
        h1 {
            color: #333;
            text-align: center;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            border: 1px solid #999;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
        h2 {
            text-align: right;
            margin-top: 20px;
        }
.customer-info {
        font-family: 'Helvetica', 'Arial', sans-serif;
        line-height: 1.6;
        margin-bottom: 20px;
    }
    .customer-info p {
        margin: 0 0 10px 0;
        color: #333;
    }
    .customer-info label {
        font-weight: bold;
    }
    </style>")
			' You can add style tags here for styling your PDF content
			htmlStringBuilder.Append("</head>")
			htmlStringBuilder.Append("<body>")
			htmlStringBuilder.Append("<h1>Invoice</h1>")
			htmlStringBuilder.Append("<div class='customer-info'>")
			htmlStringBuilder.Append($"<p><strong>Customer Name:</strong> {customerName}</p>")
			htmlStringBuilder.Append($"<p><strong>Customer Email:</strong> {customerEmail}</p>")
			htmlStringBuilder.Append($"<p><strong>Customer Address:</strong> {customerAddress}</p>")
			htmlStringBuilder.Append($"<p><strong>Customer Phone:</strong> {customerPhone}</p>")
			htmlStringBuilder.Append("</div>")
			' Add the invoice items
			htmlStringBuilder.Append("<table border='1'><tr><th>Item ID</th><th>Description</th><th>Quantity</th><th>Unit Price</th><th>Total Price</th></tr>")
			For Each row As DataGridViewRow In invoiceDataGridView.Rows
				If row.IsNewRow Then
					Continue For ' Skip the new row placeholder
				End If
				htmlStringBuilder.Append("<tr>")
				htmlStringBuilder.Append($"<td>{row.Cells ("itemIdColumn").Value}</td>")
				htmlStringBuilder.Append($"<td>{row.Cells ("descriptionColumn").Value}</td>")
				htmlStringBuilder.Append($"<td>{row.Cells ("quantityColumn").Value}</td>")
				htmlStringBuilder.Append($"<td>{row.Cells ("unitPriceColumn").Value:C2}</td>")
				htmlStringBuilder.Append($"<td>{row.Cells ("totalPriceColumn").Value:C2}</td>")
				htmlStringBuilder.Append("</tr>")
			Next row
			htmlStringBuilder.Append("</table>")
			' Add the total amount
			htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>")
			' Close the HTML string
			htmlStringBuilder.Append("</body></html>")
			' Use IronPDF to convert the HTML string to a PDF document
			Dim renderer = New IronPdf.ChromePdfRenderer()
			Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString())
			' Save the PDF to a file
			Dim savePath As String = Path.Combine($"F:\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf") ' to avoid file name conflicts and save to desktop
			pdfDocument.SaveAs(savePath)
			' Show a success dialog
			MessageBox.Show("The invoice has been successfully saved to your desktop.", "Invoice Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
VB   C#

アプリケーションの実行と請求書の生成

Windows Formsアプリケーションが開発され、IronPDFライブラリが統合されると、アプリケーションの実行とPDF請求書の生成は簡単なプロセスです。 ユーザーはアプリケーションのユーザーインターフェースを操作してデータを入力し、目的の出力を生成します。 通常、プロセスは以下のように展開します:

アプリケーションの起動

アプリケーションを開始するには、Visual Studio 内で実行するか、またはコンパイルされた実行ファイルを実行します。 (.exe) Windows環境から直接。 アプリケーションのフォーム表示、ユーザーの操作が可能です。

請求書データの入力

フォームの上部にある指定されたテキストボックスに、お客様の名前、住所、メールアドレス、電話番号を含む顧客詳細を入力してください。 フォームの「請求書アイテムを追加」セクションにある「アイテムID」、「説明」、「数量」、「単価」フィールドに入力して、請求書アイテムを追加してください。

「アイテムを追加」をクリックして、アイテムを請求書リストに含めます。DataGridViewは新しいアイテム、その詳細、および計算された合計価格を表示するように更新されます。必要なすべてのアイテムを請求書に追加するために、このプロセスを繰り返してください。「合計金額」ラベルはリストされたアイテムの累計総額を反映するように動的に更新されます。

.NET ソフトウェア開発(開発者向けの動作方法):図 4 - 請求書データ

PDF請求書の生成

すべての項目が追加され、顧客情報が完了したら、「請求書を生成」をクリックしてください。 アプリケーションはデータをCSSでスタイル設定されたHTML形式にコンパイルします。 IronPDFはHTML文字列をPDFドキュメントに変換します。 それはChromeエンジンでレンダリングされており、最新のウェブ標準に高い忠実度を確保しています。

生成された請求書の表示

PDFの生成後、 アプリケーションはPDFファイルを保存します。保存場所は通常、アプリケーションと同じディレクトリ内か、ユーザーが定義したパスになります。 PDF請求書が正常に保存されたことを通知する成功メッセージが表示されます。 ユーザーは保存された場所に移動して、請求書を表示または配布できます。

.NETソフトウェア開発(開発者向けの仕組み):図5 - 保存された請求書ダイアログ

PDFを出力

出力PDFには、顧客の情報が上部に表示され、続いて購入商品の詳細な表が記載されています。この表には、商品説明、数量、価格が含まれています。 請求書の合計金額は、ドキュメントの末尾に記載されており、顧客が支払うべき金額が明確に示されています。 PDFは、コード内で定義されたCSSを活用して、請求書が機能的であるだけでなく、美しく見えるように、クリーンでプロフェッショナルなスタイルに整えられています。

.NET ソフトウェア開発 (開発者向けの仕組み): 図 6 - PDF出力

Windows Formsプロジェクトを実行可能ファイルに変換する

Windows Forms アプリケーションを徹底的にテストし、データ入力、PDF 生成、および出力などのすべての機能が完璧に動作していることを確認した後、次の段階はプロジェクトを実行可能なファイルとしてパッケージ化することです。 (.exe) ファイル。この変換プロセスは .NET フレームワーク内で効率化されており、Windows マシンへのインストールおよび使用の準備が整ったアプリケーションを確保します。

ここでは、実行可能ファイルを作成するためのステップバイステップのアプローチを紹介します:

  1. アプリケーションのビルド: 「Build」メニューに移動し、「Build Solution」を選択します。これにより、コードがアセンブリにコンパイルされ、必要な最適化が実行されます。

    .NETのソフトウェア開発(開発者向けの仕組み):図7 - ソリューションのビルド

  2. 実行ファイルを見つける: ビルドが完了したら、プロジェクトのディレクトリ内にある『bin\Debug\net8.0』フォルダーに移動します。 ここでは、アプリケーションを実行するために必要な.exeファイルおよびその他の依存関係が見つかります。

    .NETソフトウェア開発(開発者向けの動作方法):図8 - 実行ファイルの場所

  1. 実行ファイルのテスト: .exeファイルを開発環境外の別のコンピューターで実行して、正しく動作することを確認するのは良い習慣です。

  2. 配布の準備: 追加の依存関係が必要ない場合は、.exeファイルを直接共有することができます。 しかし、よりプロフェッショナルなアプローチを求める場合は、Visual StudioのセットアッププロジェクトやInno SetupやWiXツールセットのようなサードパーティのインストーラパッケージを使用してインストーラを作成することを検討してください。 インストーラーは、インストールプロセスを管理し、ショートカットを作成し、必要に応じてWindows レジストリへの登録などの複雑な作業を処理できます。

    これらの手順に従うことで、Windows Forms アプリケーションは単一の実行可能ファイルに圧縮され、共有および利用する準備が整います。 この変換は、開発プロセスの集大成を示し、開発マシン上のプロジェクトから、複数のWindows環境に効率的に配布され、インストールできるデプロイ可能なソフトウェアに移行するものです。

結論

.NETソフトウェア開発(開発者向けの仕組み):図9 - ライセンス

結論として、IronPDFと.NET Frameworkを使用してPDF請求書を生成するためのWindows Formsアプリケーションの開発は、ソフトウェア開発の原則の実用的な応用を示しています。 このプロジェクトは、.NETエコシステムの多用途性とパワーを示すだけでなく、IronPDFのようなサードパーティライブラリーを統合して機能を拡張し、特定のビジネスニーズに対応する方法を開発者に示します。

以下の手順に従うことで、ユーザーインターフェースの設定からPDF生成の実装、およびアプリケーションを実行可能ファイルにパッケージ化するまで、開発者は機能的でユーザーフレンドリーなアプリケーションを作成できます。 このプロセスは、現実世界の問題を解決するために堅牢なプログラミングフレームワークと革新的なライブラリを組み合わせることの重要性を強調しており、最終的に効果的かつ効率的な製品を提供します。

IronPDFは寛大に 無料試用 開発者が機能を調査し、自分のニーズにどのように最適に合うかを判断するために。 利点を実感し、IronPDFの本番環境への統合を準備ができましたら、ライセンスは$749から始まります。

< 以前
Dotnet NuGet(開発者向けの動作方法)
次へ >
C# パターン マッチング式(開発者向けの仕組み)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >