.NET 幫助

.NET軟體開發(對開發人員的運作方式)

發佈 2024年3月26日
分享:

.NET框架軟件開發 代表一個強大且多功能的框架,由微軟支援,使 .NET 開發者能夠創建跨越多種平台、操作系統和設備的健壯、高質量應用程式。這個軟體開發框架設計得很全面,提供了工具、函式庫和 API,軟體開發者可以利用它們在 .NET 平台上有效率地構建 web、桌面和移動應用程式。

支援多種程式語言,包括 C#、Visual Basic 和 F#,.NET 開發擴展了其靈活性,確保開發者可以使用他們偏好的語言工作,同時受益於 .NET Core 生態系統的豐富功能。在本教程中,我們將看到 IronPDF 用以展示 .NET 開發解決實際問題的運作情形。

理解 .NET 軟體開發生態系統

.NET 生態系統,作為一個主要的 .NET 實作,是一個廣泛且包羅萬象的平台,包含各種旨在促進跨不同操作系統應用開發的元件和技術。其核心是 .NET Framework 和 .NET Core,這兩者是運行 .NET 應用的主要引擎,提供一個通用語言運行時。 (公共語言運行庫) 管理代碼執行並提供像記憶體管理、類型安全、異常處理等服務。

通用語言執行平台 (公共語言運行庫)

CLR 是 .NET 架構中的關鍵元素,使 .NET 程式碼能夠在不同操作系統上執行。它會編譯通用中介語言 (通用中間語言 (CIL)) 轉換成宿主機器可以直接執行的本機機器代碼。這個過程確保了 .NET 應用程式可以在各種平台上無縫運行,從主要的移動操作系統到 Windows 網頁伺服器。

跨平台框架

.NET Core 以跨平台框架的姿態崛起,允許 .NET 應用程式在 Linux、macOS 和 Windows 上運行。這種適應性使 .NET 成為開發者希望在不同裝置和平台上觸及更廣泛受眾的吸引選擇。有了 .NET Core,應用程式可以在任何受支持的操作系統上開發和部署,增強 .NET 軟體開發的覆蓋範圍和靈活性,這得益於廣泛的 .NET 社區。

集成開發環境 (集成開發環境)

Visual Studio 是首屈一指的集成開發環境 (集成開發環境) 用於 .NET 開發。它為開發人員提供了強大的代碼編寫、調試和部署 .NET 應用程式的工具。Visual Studio 支援多種編程語言,並提供了大量功能來構建網頁、桌面和移動應用程式,使其成為 .NET 開發人員不可或缺的工具。

使用 .NET 建立應用程式

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

使用 ASP.NET 進行網頁開發

ASP.NET 是 .NET 框架的一部分,專為構建動態網頁和應用程式而設計。它允許開發者創建響應迅速且可擴展的網頁應用程式,可以處理大量的流量。ASP.NET Core 是 ASP.NET 的開源版本,為構建跨平臺的網頁應用程式帶來了額外的功能,使得在 Windows、Linux 和 macOS 上開發和部署網頁應用程式成為可能。

桌面應用程式開發

.NET 提供了兩種主要的桌面應用程式開發方式:Windows Forms 和 Windows Presentation Foundation (WPF)Windows Forms 提供了一種簡單的方法來創建具有豐富圖形用戶界面的桌面應用程序,而 WPF 則使用 XAML (可扩展应用程序标记语言) 以啟用具有先進圖形和動畫的視覺上吸引人的使用者界面開發。

行動應用程式開發

對於行動開發,.NET 通過 Xamarin 框架延伸至主要的行動作業系統,現在整合為 .NET MAUI。 (跨平台應用程式使用者介面)這種方法允許開發者在 iOS、Android 和 Windows 之間重複使用代碼,從而簡化了創建提供原生性能和用戶體驗的移動應用程式的過程。

雲端和微服務

.NET 也非常適合開發在雲端運行的應用程序。通過對 Azure 和其他雲平台的支持,開發人員可以構建可擴展的分佈式應用程序,利用雲計算資源。ASP.NET Core 在開發微服務方面發揮著重要作用,提供輕量級、模塊化和獨立部署的服務,這些服務可以在雲環境中擴展。

機器學習和人工智慧

.NET 生態系統包含了 ML.NET,一個機器學習框架,允許開發人員將自定義機器學習模型集成到他們的 .NET 應用中。這種集成打開了創建智慧應用程式的可能性,這些應用程式能夠進行預測分析、自然語言處理等,利用 .NET 框架內的人工智慧功能。

使用 IronPDF 增強 .NET 軟體開發

.NET 軟體開發(對開發人員的工作方式):圖 1 - IronPDF

在充滿活力的 .NET 軟體開發生態系統中,直接在應用程式內生成、操作和管理 PDF 文件的能力帶來了顯著的優勢。IronPDF 是為 .NET 開發人員設計的強大庫,它無縫整合到這個環境中,提供了一種高效的方法來從 .NET 應用程式(包括使用 Windows Forms 構建的應用程式)創建 PDF。

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

IronPDF 代表了 .NET 生態系統的靈活性和強大功能,為開發人員提供了直觀的 API 來 從 HTM 生成 PDF 文件 L、圖像、文字,甚至 ASP.NET 網頁。這種功能在需要動態文件創建的情況下特別有用,例如在桌面應用程序中生成發票、報告或個性化文件。

使用 IronPDF 建立 Windows Form 發票生成器

結合 .NET 軟體開發與 IronPDF 的應用,Windows Form 發票生成器展示了實際應用的例子。該應用允許用戶輸入客戶信息、購買項目和價格等詳細資料,然後一鍵生成專業的 PDF 發票。

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

首先在 Visual Studio 中建立一個新的 Windows Forms 專案。這是您的基礎,您將在此設計發票生成器的使用者介面。設計表單以包含客戶和項目詳細資料的必要輸入字段,以及生成 PDF 的按鈕。這是我們的發票生成器 UI:

.NET 軟體開發(它如何運作於開發者):圖 2 - 發票生成器 Windows 表單輸出

Windows Forms 應用程序的用戶界面經過精心設計,以確保易於使用和功能性。主窗口標題為「Invoice Generator」,分為不同的部分以提供無縫的用戶體驗。

客戶信息區段

在頂部,表單包含「客戶姓名」、「客戶地址」、「客戶電子郵件」和「客戶電話號碼」欄位。這個區域專門用於捕捉將在生成的發票中突顯的關鍵客戶詳細信息。

添加發票項目

在客戶信息的下方,有一個標有「添加發票項目」的區域。這裡用戶可以輸入各個項目的詳細信息,如「項目 ID」、「描述」、「數量」和「單價」。這些字段旁邊有一個「添加項目」按鈕,允許用戶將輸入的項目添加到下面的發票列表中。

發票項目清單

表單的中央部分設有“發票信息”部分,顯示一個表格,其中輸入的項目在添加時會顯示出來。表格列包括“項目編號”,“描述”,“數量”,“單價”和“總價”,最後一列根據數量和單價自動計算。一個標題為“選擇日期”的日期選擇器允許用戶指定發票日期,增加了文檔的特定性。

發票操作

在表單的底部,標籤顯示 '總金額',並在項目添加或刪除時動態更新。這確保用戶能即時匯總發票的總價值。此外,'生成發票' 按鈕會提示應用程式使用IronPDF庫,根據輸入的數據創建發票的PDF版本。

這個用戶介面不僅功能強大,還具有直觀性,使用戶能輕鬆地與應用程式互動,且不需要高深的學習曲線。它設計得能容納所有發票生成必要的信息,同時提供從數據輸入到PDF創建的明確而簡單的路徑。

在您的專案中新增IronPDF

在您設定專案後,下一步就是將IronPDF導入其中。這可以透過NuGet來完成,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
    // 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發票

點擊「生成發票」後,應用程序會執行 btnInvoice_Click 事件處理程序,並使用 StringBuilder 構建 HTML 字符串。該字符串包括客戶的詳細信息和一個帶樣式的 HTML 表格,該表格由 DataGridView 中的發票項目填充。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發票

點擊‘生成發票’ 一旦所有項目添加完成並且客戶信息完善,應用程序會將數據編譯成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 框架中得到簡化,確保您的應用程式準備好在 Windows 機器上安裝和使用。

以下是創建可執行檔案的逐步方法:

  1. 建構應用程式: 進入「建構」選單並選擇「建構方案」。這將程式碼編譯成組件並執行必要的最佳化。

.NET軟體開發(對開發人員的運作方式):圖7 - 建置解決方案

  1. 定位可执行文件: 一旦构建完成,导航到项目目录内的 'bin\Debug\net8.0' 文件夹。在这里,你会找到 .exe 文件及运行应用程序所需的其他依赖项。

.NET 軟體開發(開發人員如何使用):圖 8 - 可執行檔位置

  1. 測試可執行檔: 最佳實踐是將 .exe 檔案在不同的機器上運行,以確認它在開發環境之外也能正確運行。

  2. 準備分發: 對於分發,如果不需要額外的依賴項,你可以直接分享 .exe 檔案。然而,為了更專業的做法,可以考慮使用 Visual Studio 中的設置項目或第三方安裝包(如 Inno Setup 或 WiX Toolset)來創建安裝程序。安裝程序可以管理安裝過程,創建快捷方式,並處理其他複雜性,例如註冊到 Windows Registry(如果需要)。

透過遵循這些步驟,你的 Windows Forms 應用程式被濃縮成一個可執行檔,準備好被分享和使用。這次轉換標誌著開發過程的完成,從你的開發機器上的專案過渡到可以有效分發和安裝在各種 Windows 環境中的可部署軟體。

結論

.NET 軟體開發(運作方式):圖 9 - 授權

總而言之,使用 IronPDF 和 .NET 框架來開發生成 PDF 發票的 Windows Forms 應用程式,即為軟體開發原則的一個實際應用範例。本專案不僅展示了 .NET 生態系統的多功能性和強大能力,還證明了開發人員如何整合第三方庫如 IronPDF 來擴展功能並滿足特定的業務需求。

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

IronPDF 慷慨地提供一個 免費試用 供開發人員探索其功能並決定如何最適合他們的需求。一旦您體驗過其優點並準備將 IronPDF 整合到您的生產環境中,授權從 $749 開始。

< 上一頁
Dotnet NuGet(開發人員如何使用)
下一個 >
C# 模式匹配表达式 (开发人员使用方法)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >