跳至頁尾內容
.NET幫助

.NET 軟體開發(對於開發者的運行原理)

.NET Framework 軟體開發 代表著一個強大而多元的框架,由 Microsoft 支持,使 .NET 開發者能夠建立穩定且高質量的應用程式,涵蓋各種平台、操作系統和裝置。 這個軟體開發框架設計得非常全面,提供了工具、程式庫和 APIs,讓軟體開發者能夠在 .NET 平台上高效地建立網頁、桌面和移動應用程式。

支援多種程式語言,包括 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 作為 .NET 開發的主要整合開發環境 (IDE)。 它為開發者提供了強大的工具,用於編寫程式碼、除錯和部署 .NET 應用程式。 Visual Studio 支援多種編程語言,並提供多樣的功能以建立網頁、桌面和移動應用程式,是 .NET 開發者不可或缺的工具。

使用 .NET 建立應用程式

在 .NET 平台上建立應用程式涉及利用這個框架提供的各種工具、程式庫和程式語言,如 Visual Basic,展示其全面的生態系統。 這種多功能性使軟體開發者能夠構建各種型別的 .NET 應用程式,從網頁和桌面應用程式到基於雲的和移動解決方案。

使用 ASP.NET 進行網頁開發

ASP.NET 作為 .NET Framework的一個重要組成部分,專為構建動態網頁和應用程式而設計。 它允許開發者建立具有響應性和可擴展性的網頁應用程式,能夠處理大量的流量。 ASP.NET Core 是 ASP.NET 的開源版本,增加了構建跨平台網頁應用程式的功能,使得在 Windows、Linux 和 macOS 上開發和部署網頁應用程式成為可能。

桌面應用程式開發

.NET 提供了兩種主要方法來建立桌面應用程式:Windows Forms 和 Windows Presentation Foundation (WPF)。 Windows Forms 提供了一種簡單的方法來建立具有豐富圖形使用者介面的桌面應用程式,而 WPF 使用 XAML(可擴展應用程式標記語言)來啟用開發具有高級圖形和動畫的視覺上吸引人的使用者介面。

移動應用程式開發

對於移動開發,.NET 通過 Xamarin 框架將其觸及範圍延伸至主要的移動操作系統,現在整合為 .NET MAUI (多平台應用 UI)。 這種方法允許開發者在 iOS、Android 和 Windows 間重複使用程式碼,簡化了建立具有原生性能和使用者體驗的移動應用程式的過程。

雲端和微服務

.NET 也適合於開發運行於雲端的應用程式。 支援 Azure 和其他雲平台,開發者可以構建具有擴展性、分佈式的應用程式,利用雲計算資源。 ASP.NET Core 在開發微服務中扮演重要角色,提供輕量級、模組化和可以獨立部署的服務,可以在雲端環境中擴展。

機器學習和人工智慧

.NET 生態系統涵蓋了 ML.NET,一個機器學習框架,允許開發者將自定義機器學習模型整合到他們的 .NET 應用程式中。 這種整合開啟了建立具有智能分析、自然語言處理等功能的智能應用程式的可能性,利用 .NET Framework內的人工智慧的力量。

用 IronPDF 增強 .NET 軟體開發

.NET 軟體開發(面向開發者如何運作):圖 1 - IronPDF

.NET 軟體開發的活躍生態系統中,在應用程式內直接生成、操作和管理 PDF 文件的能力提供了一個重要的優勢。 IronPDF 作為一個為 .NET 開發者設計的強大程式庫,無縫地融入這個環境,提供了一種有效的方法來從 .NET 應用程式, 包括 Windows Forms 構建的應用程式中建立 PDFs。

IronPDF 在 .NET 應用程式中的角色

IronPDF 是 .NET 生態系統靈活性和力量的證明,提供開發者一個直觀的 API,從 HTML、圖像、文字甚至 ASP.NET 網頁中生成 PDF 文件。 這種能力在需要動態文件建立的場景中特別有用,例如在桌面應用程式中生成發票、報告或個性化文件。

使用 IronPDF 構建 Windows 表單發票生成器

生成發票的 Windows 表單應用程式是 .NET 軟體開發與 IronPDF 結合的實際應用範例。 該應用程式允許使用者輸入客戶資訊、購買品項和價格,然後一鍵生成專業的 PDF 發票。

設置您的 Windows 表單專案並設計使用者介面

首先在 Visual Studio 中建立一個新的 Windows Forms 專案。 這是您的基礎,您將在這裡打造您的發票生成器的使用者介面。 設計您的表單以包含客戶和品目詳情所需的輸入欄位,並附加一個用於生成 PDF 的按鈕。 這就是我們的發票生成器使用者介面:

.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"按鈕,允許使用者將輸入的項目新增到下方的發票列表中。

發票項目清單

表單的中間部分設有"Invoice Information"部分,展示了一個表格,顯示項目輸入後加入的項目。 表格欄包括"Item ID"、"Description"、"Quantity"、"Unit Price"和"Total Price",最後一欄是基於數量和單價自動計算的。標題為"Select Date"的日期選擇器允許使用者指定發票日期,增加了文件的特性。

發票操作

表單底部顯示的"Total Amount"標籤隨著項目新增或移除而動態更新。 這確保使用者擁有發票總價值的即時計算。 此外,"Generate Invoice"按鈕促使應用程式使用 IronPDF 程式庫根據輸入的資料建立發票的 PDF 版本。

這個使用者界不僅功能齊全,而且直觀,使用者可以輕鬆操作應用程式,不需要陡峭的學習曲線。 它被設計來容納所有發票生成所需的資訊,同時提供從資料輸入到 PDF 建立的清楚直接的路徑。

將 IronPDF 新增到您的專案中

設置您的專案後,接下來的步驟是引入 IronPDF。 這可以通過 NuGet 完成,Visual Studio 的整合 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
    // Add columns specifying the details to be displayed in the invoice
    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; // 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 to manage deletion of items
    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
    // Add columns specifying the details to be displayed in the invoice
    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; // 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 to manage deletion of items
    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
	' Add columns specifying the details to be displayed in the invoice
	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 ' 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 to manage deletion of items
	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
$vbLabelText   $csharpLabel

新增發票項目

當使用者輸入某個項目的詳細資訊並點擊"Add Item"時,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);
    }
    // Display the total amount accumulated
    lblTotalAmount.Text = $"{totalAmount:C2}";
}

private void btnAddItem_Click(object sender, EventArgs e)
{
    // Collect data from input controls
    string itemId = txtItemID.Text;
    string description = txtDescription.Text;
    int quantity = (int)numericUpDownQuantity.Value;
    decimal unitPrice;
    // Validate the collected data
    bool isUnitPriceValid = decimal.TryParse(txtUnitPrice.Text, out unitPrice);
    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);
    // Clear the input fields after adding the item to the grid
    txtItemID.Clear();
    txtDescription.Clear();
    txtUnitPrice.Clear();
    numericUpDownQuantity.Value = 0;
    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);
    }
    // Display the total amount accumulated
    lblTotalAmount.Text = $"{totalAmount:C2}";
}

private void btnAddItem_Click(object sender, EventArgs e)
{
    // Collect data from input controls
    string itemId = txtItemID.Text;
    string description = txtDescription.Text;
    int quantity = (int)numericUpDownQuantity.Value;
    decimal unitPrice;
    // Validate the collected data
    bool isUnitPriceValid = decimal.TryParse(txtUnitPrice.Text, out unitPrice);
    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);
    // Clear the input fields after adding the item to the grid
    txtItemID.Clear();
    txtDescription.Clear();
    txtUnitPrice.Clear();
    numericUpDownQuantity.Value = 0;
    CalculateTotalAmount();
}
Imports System

Public Sub AddItemToInvoice(ByVal itemId As String, ByVal description As String, ByVal quantity As Integer, ByVal unitPrice As Decimal)
	Dim totalPrice As Decimal = quantity * unitPrice
	invoiceDataGridView.Rows.Add(itemId, description, quantity, unitPrice, totalPrice)
End Sub

Private Sub CalculateTotalAmount()
	Dim totalAmount As Decimal = 0D
	For Each row As DataGridViewRow In invoiceDataGridView.Rows
		totalAmount += Convert.ToDecimal(If(row.Cells("totalPriceColumn").Value, 0))
	Next row
	' Display the total amount accumulated
	lblTotalAmount.Text = $"{totalAmount:C2}"
End Sub

Private Sub btnAddItem_Click(ByVal sender As Object, ByVal e As EventArgs)
	' Collect data from input controls
	Dim itemId As String = txtItemID.Text
	Dim description As String = txtDescription.Text
	Dim quantity As Integer = CInt(Math.Truncate(numericUpDownQuantity.Value))
	Dim unitPrice As Decimal = Nothing
	' Validate the collected data
	Dim isUnitPriceValid As Boolean = Decimal.TryParse(txtUnitPrice.Text, unitPrice)
	If String.IsNullOrEmpty(itemId) OrElse String.IsNullOrEmpty(description) OrElse quantity <= 0 OrElse Not isUnitPriceValid OrElse unitPrice <= 0 Then
		MessageBox.Show("Please enter valid data for all fields.", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.Warning)
		Return
	End If
	' Add data to the DataGridView
	AddItemToInvoice(itemId, description, quantity, unitPrice)
	' Clear the input fields after adding the item to the grid
	txtItemID.Clear()
	txtDescription.Clear()
	txtUnitPrice.Clear()
	numericUpDownQuantity.Value = 0
	CalculateTotalAmount()
End Sub
$vbLabelText   $csharpLabel

生成 PDF 發票

點擊 "Generate Invoice" 時,應用執行 btnInvoice_Click 事件處理器,構建一個 HTML 字串,使用 StringBuilder。 這個字串包含了顧客細節以及 DataGridView 中發票項填充的樣式化 HTML 表格。 IronPDF 的渲染器然後將此 HTML 轉換為 PDF 文件,並保存到指定路徑。 應用程式通過一個消息確認發票建立成功。

private void btnInvoice_Click(object sender, EventArgs e)
{
    IronPdf.License.LicenseKey = "your-license-key"; // Replace with your IronPDF license key
    var customerName = txtName.Text;
    var customerEmail = txtEmail.Text;
    var customerAddress = txtAddress.Text;
    var customerPhone = txtPhone.Text;
    var htmlStringBuilder = new StringBuilder();
    htmlStringBuilder.Append("<html>");
    htmlStringBuilder.Append("<head>");
    htmlStringBuilder.Append("<title>Invoice</title>");
    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 { line-height: 1.6; margin-bottom: 20px; }
            .customer-info p { margin: 0 0 10px 0; color: #333; }
            .customer-info label { font-weight: bold; }
        </style>");
    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>");
    htmlStringBuilder.Append("<table><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; 
        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>");
    htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>");
    htmlStringBuilder.Append("</body></html>");
    var renderer = new IronPdf.ChromePdfRenderer();
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString());
    string savePath = Path.Combine($"F:\\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf");
    pdfDocument.SaveAs(savePath);
    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 = "your-license-key"; // Replace with your IronPDF license key
    var customerName = txtName.Text;
    var customerEmail = txtEmail.Text;
    var customerAddress = txtAddress.Text;
    var customerPhone = txtPhone.Text;
    var htmlStringBuilder = new StringBuilder();
    htmlStringBuilder.Append("<html>");
    htmlStringBuilder.Append("<head>");
    htmlStringBuilder.Append("<title>Invoice</title>");
    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 { line-height: 1.6; margin-bottom: 20px; }
            .customer-info p { margin: 0 0 10px 0; color: #333; }
            .customer-info label { font-weight: bold; }
        </style>");
    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>");
    htmlStringBuilder.Append("<table><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; 
        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>");
    htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>");
    htmlStringBuilder.Append("</body></html>");
    var renderer = new IronPdf.ChromePdfRenderer();
    var pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString());
    string savePath = Path.Combine($"F:\\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf");
    pdfDocument.SaveAs(savePath);
    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 = "your-license-key" ' Replace with your IronPDF license key
	Dim customerName = txtName.Text
	Dim customerEmail = txtEmail.Text
	Dim customerAddress = txtAddress.Text
	Dim customerPhone = txtPhone.Text
	Dim htmlStringBuilder = New StringBuilder()
	htmlStringBuilder.Append("<html>")
	htmlStringBuilder.Append("<head>")
	htmlStringBuilder.Append("<title>Invoice</title>")
	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 { line-height: 1.6; margin-bottom: 20px; }
            .customer-info p { margin: 0 0 10px 0; color: #333; }
            .customer-info label { font-weight: bold; }
        </style>")
	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>")
	htmlStringBuilder.Append("<table><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
		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>")
	htmlStringBuilder.Append($"<h2>Total Amount: {lblTotalAmount.Text}</h2>")
	htmlStringBuilder.Append("</body></html>")
	Dim renderer = New IronPdf.ChromePdfRenderer()
	Dim pdfDocument = renderer.RenderHtmlAsPdf(htmlStringBuilder.ToString())
	Dim savePath As String = Path.Combine($"F:\Invoice_{DateTime.Now:yyyyMMddHHmmss}.pdf")
	pdfDocument.SaveAs(savePath)
	MessageBox.Show("The invoice has been successfully saved to your desktop.", "Invoice Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
$vbLabelText   $csharpLabel

運行應用程式並生成發票

在開發出 Windows Forms 應用並整合 IronPDF 程式庫後,運行應用並生成 PDF 發票是一個簡單明了的過程。 使用者與應用程式的使用者介面互動以輸入資料並生成所需的輸出。 這一過程通常是這樣展開的:

啟動應用程式

通過在 Visual Studio 中運行應用程式或直接從 Windows 環境執行編譯好的可執行文件 (.exe) 開始應用程式。 應用程式的表單顯示出來,準備讓使用者進行互動。

輸入發票資料

在表單頂部的指定文字框中輸入客戶詳細資訊,包括客戶姓名、地址、電子郵件和電話號碼。 通過填寫表單中"Add Invoice Item" 部分的"Item ID"、"Description"、"Quantity"和"Unit Price"欄位來新增發票項。

點擊"Add Item" 來將項目新增到發票清單中。DataGridView 將更新顯示新項目、其詳細資訊和計算的總價。重複此過程以將所有必要的項目新增到發票中。"Total Amount" 標籤將動態更新以反映列出的項目的累計總額。

.NET 軟體開發(面向開發者如何運作):圖 4 - 發票資料

生成 PDF 發票

點擊 "Generate Invoice" 當所有項目都已新增且客戶資訊完成時。 應用將資料編譯成 HTML 格式,搭配 CSS 樣式。 IronPDF 負責將 HTML 字串轉換為 PDF 文件。 它採用 Chrome 引擎進行渲染,確保對現代網路標準的高度一致性。

查看生成的發票

完成 PDF 生成後,應用保存 PDF 文件到指定位置,通常與應用在同一目錄或使用者定義的路徑。 一個 成功消息 出現以通知使用者 PDF 發票已成功保存。 使用者然後可以導航到保存位置查看或分發發票。

.NET 軟體開發(面向開發者如何運作):圖 5 - 保存的發票對話框

輸出 PDF

輸出 PDF 在頂部顯示客戶資訊,接著是購買品項的詳細表,包括描述、數量和價格。 發票總額 列於文件結尾,清晰地顯示客戶需要支付的金額。 PDF 設計成乾淨且專業,使用程式碼內定義的 CSS 確保發票不僅功能齊全而且美觀。

.NET 軟體開發(面向開發者如何運作):第 6 圖 - PDF 輸出

將 Windows Forms 專案轉換為可執行文件

在徹底測試您的 Windows Forms 應用程式並確保資料輸入、PDF 生成和輸出等所有功能運行良好之後,下一步是將您的項目打包成可執行 (.exe) 文件。此轉換過程在 .NET Framework內部進行了精簡,確保您的應用程式已準備好安裝在 Windows 機器上並被使用。

以下是建立可執行文件的步驟指南:

  1. 構建應用程式: 前往 "Build" 選單,選擇 "Build Solution"。這將程式碼編譯為程式集並進行必要的優化。

.NET 軟體開發(面向開發者如何運作):圖 7 - 建置方案

  1. 定位可執行文件: 一旦建置完成,導航到專案目錄中的 "bin\Debug\net8.0" 資料夾。 在這裡,您會找到 .exe 文件及運行應用所需的其他依賴項。

.NET 軟體開發(面向開發者如何運作):圖 8 - 可執行位置

  1. 測試可執行文件: 最好在不同的機器上運行 .exe 文件,以確認它在開發環境之外操作正常。
  2. 準備分發: 若無需其他依賴項,您可以直接共享 .exe 文件。 不過,出於更專業的方法,考慮使用 Visual Studio 中的設置專案或第三方安裝包,如 Inno Setup 或 WiX Toolset,建立安裝程式。 安裝程式可以管理安裝過程、建立快捷方式,並處理其他複雜性,如需要時註冊到 Windows 註冊表。

按照這些步驟,您的 Windows Forms 應用程式被壓縮為單個可執行文件,準備共享和使用。 此轉換標誌著開發過程的結束,從您開發中的項目轉變為可以有效發佈和安裝在多種 Windows 環境中的可部署軟體。

結論

.NET 軟體開發(面向開發者如何運作):第 9 圖 - 許可證

總結來說,使用 IronPDF 和 .NET Framework 開發生成 PDF 發票的 Windows 表單應用程式展示了軟體開發原則的實際應用。 這個項目不僅呈現了 .NET 生態系統的多樣性和強大力量,還展示了開發者如何整合第三方程式庫如 IronPDF 來擴展功能以滿足特定業務需求。

通過遵循所列步驟,從設置使用者介面到實現 PDF 生成並打包應用成可執行文件,開發者可以建立一個功能齊全且使用者友好的應用程式。 這一過程突顯了結合強大的編程框架與創新程式庫以解決現實問題的重要性,最終交付一個既有效又高效的產品。

IronPDF 慷慨地提供 免費試用 PDF 生成功能 讓開發者探索其功能並確定其如何最好地滿足他們的需求。 當您體驗到這些好處並準備將 IronPDF 整合到您的生產環境中時,許可證從實惠的價格選項開始提供。

常見問題

如何在C#中將HTML轉換為PDF?

您可以使用IronPDF的RenderHtmlAsPdf方法將HTML字串轉換為PDF。您還可以使用RenderHtmlFileAsPdf將HTML檔案轉換為PDF。

使用.NET Core進行跨平台開發有哪些好處?

.NET Core允許您在多個平台上運行應用程式,如Linux、macOS和Windows,這使得它成為開發者希望通過單一程式碼庫覆蓋更廣泛受眾的多才多藝的選擇。

如何從Windows Form應用程式中生成PDF?

使用IronPDF,您可以通過將程式庫整合到您的專案中,並利用其方法將表單資料或HTML內容轉換為PDF文件,來從Windows Form應用程式生成PDF。

什麼使.NET成為構建網頁應用程式的理想框架?

.NET,尤其是ASP.NET,提供了一個強大的框架來構建動態和可擴展的網頁應用程式。它提供了用於伺服器端腳本、驗證、資料處理等的內建工具。

如何增強我的.NET應用程式的文件生成功能?

在您的.NET應用程式中整合像IronPDF這樣的程式庫可以顯著增強其文件生成功能,使您能夠直接在應用程式內建立、操作和管理PDF文件。

可以使用.NET來進行移動應用程式開發嗎?

是的,.NET通過Xamarin框架支持移動應用程式開發,而Xamarin現已成為.NET MAUI的一部分。這允許在iOS、Android和Windows上建立具有原生效能的跨平台移動應用程式。

共通語言執行環境(CLR)在.NET中有什麼重要性?

共通語言執行環境(CLR)在.NET中至關重要,因為它通過將編譯後的程式碼轉換為本機機器程式碼來管理程式的執行,確保跨不同操作系統的相容性。

如何使用NuGet將PDF生成整合到我的.NET專案中?

您可以使用NuGet來安裝像IronPDF這樣的程式庫,將PDF生成整合到您的.NET專案中。這使得在Visual Studio中新增PDF功能變得方便和簡單。

使用Windows Forms建立一個PDF發票生成器的步驟是什麼?

該過程包括設置一個Windows Forms專案,設計介面,通過NuGet新增所需的程式庫,實施資料輸入和發票生成的邏輯,並使用IronPDF將發票詳情轉換為PDF。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話