.NET幫助 .NET 軟件開發(對於開發者的運行原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article .NET Framework 軟體開發代表了一個由 Microsoft 支持的強大且多功能的框架,使 .NET 開發人員能夠創建橫跨各種平台、操作系統和設備的健壯、高品質應用程序。 此軟體開發框架旨在提供全面的工具、庫和 API,供軟體開發人員用於在 .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 框架的一個關鍵組成部分,專為構建動態網頁和應用程序而設計。 它允許開發人員創建能夠處理大量流量的響應式和可擴展的網頁應用程序。 ASP.NET Core,ASP.NET 的開源版本,為構建跨平台的網頁應用程序帶來了額外功能,使得可以在 Windows, Linux, 和 macOS 上開發和部署網頁應用。 桌面應用程序開發 .NET 提供了兩種主要方法來創建桌面應用程序:Windows Forms 和 Windows Presentation Foundation (WPF)。 Windows Forms 提供了一種直接的方法來創建具有豐富圖形用戶界面的桌面應用,而 WPF 使用 XAML(可擴展應用標記語言)來開發具有高級圖形和動畫的視覺上吸引人的用戶界面。 移動應用程序開發 對於移動開發,.NET 通過 Xamarin 框架擴展了對主要移動操作系統的觸及,現在已集成到 .NET 中作為 .NET MAUI(多平台應用用戶界面)。 這種方法允許開發人員跨 iOS、Android 和 Windows 重用代碼,簡化創建提供本機性能和用戶體驗的移動應用程序的過程。 雲端和微服務 .NET 也非常適合開發在雲中運行的應用程序。 通過對 Azure 和其他雲平台的支持,開發人員可以構建可擴展的分佈式應用程序,利用雲計算資源。 ASP.NET Core 在開發微服務方面發揮了重要作用,提供輕量級、模塊化和獨立可部署的服務,可以在雲環境中擴展。 機器學習和人工智能 .NET 生態系統包含 ML.NET,一個機器學習框架,允許開發人員將自定義機器學習模型整合到他們的 .NET 應用程序中。 這種集成為創建能夠進行預測分析、自然語言處理等智能應用程序提供了可能,在 .NET 框架中充分利用人工智能的力量。 使用 IronPDF 增強 .NET 軟體開發 在 .NET 軟體開發的充滿活力的生態系統中,能夠在應用程序中直接生成、操作和管理 PDF 文檔提供了顯著的優勢。 IronPDF,一個為 .NET 開發人員設計的強大庫,無縫地集成到這個環境中,提供了一種高效的方法來從 .NET 應用程序創建 PDF,包括那些用 Windows Forms 構建的應用。 IronPDF 在 .NET 應用中的角色 IronPDF 作為 .NET 生態系統靈活性和力量的見證,提供了開發人員一個直觀的 API,從 HTML、圖像、文本,甚至是 ASP.NET 網頁生成 PDF 文檔。 這種功能在需要動態生成文檔的場景中特別有用,如在桌面應用程序中生成發票、報告或個性化文檔。 使用 IronPDF 構建 Windows Form 發票生成器 用於生成發票的 Windows Form 應用程序示範了結合 IronPDF 的 .NET 軟體開發的實際應用。 此應用程序允許用戶輸入如客戶信息、購買項目和價格等詳細信息,然後一鍵生成專業的 PDF 發票。 設置您的 Windows Forms 項目並設計用戶界面 從在 Visual Studio 中創建一個新的 Windows Forms 項目開始。 這是您的基礎,您將在此構建發票生成器的用戶界面。 設計您的表單以包括客戶和項目詳細信息所需的輸入框,旁邊有一個生成 PDF 的按鈕。 這是我們的發票生成器用戶界面: Windows Forms 應用程序的用戶界面經過精心設計,確保易用性和功能性。 主窗口標題為“發票生成器”,分為不同的部分以提供無縫的用戶體驗。 客戶信息部分 在頂部,表單包括“客戶姓名”、“客戶地址”、“客戶電子郵件”和“客戶電話號碼”欄位。此區域專門用於捕獲將在生成的發票上顯著顯示的基本客戶詳細信息。 添加發票項目 就在客戶信息下方,有一個名為“添加發票項目”的區域。在這裡,使用者可以輸入單個項目的詳細信息,如“項目 ID”、“描述”、“數量”和“單價”。一個“添加項目”按鈕位於這些欄位旁,允許使用者將輸入的項目附加到下方的發票清單中。 發票項目列表 表單的中心部分是“發票信息”區,顯示一個表格,輸入的項目在添加時也會顯示出來。 表格列包括“項目 ID”、“描述”、“數量”、“單價”和“總價”,最後一列根據數量和單價自動計算。使用者可以使用標題為“選擇日期”的日期選擇器指定發票日期,增強文檔的特定性。 發票操作 表單底部的一個標籤顯示“總金額”,隨著項目的添加或刪除動態更新。 這確保用戶可以即時看到發票的總值. 此外,一個“生成發票”按鈕提示應用程序使用 IronPDF 庫根據輸入的數據生成發票的 PDF 版本。 這個用戶界面不僅功能強大而且直觀,使用戶能夠輕鬆地與應用程序互動,而不需要陡峭的學習曲線。 它旨在容納發票生成所需的所有信息,並且提供從數據輸入到 PDF 創建的清晰簡單的路徑。 向項目中添加 IronPDF 設置項目後,下一步是將 IronPDF 引入其中。 這是通過 NuGet,Visual Studio 集成的 NuGet 包管理器,讓您可以輕鬆地將 IronPDF 添加到項目中。 在包管理器控制台中運行以下命令: Install-Package IronPdf 此命令將安裝 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 添加發票項目 當用戶輸入項目詳情並點擊“添加項目”時,引發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 發票 單擊"生成發票"後,應用程序執行btnInvoice_Click事件處理器,在此處使用 StringBuilder 構建一個 HTML 字符串。 此字符串包含客戶詳細情報和一個樣式化的 HTML 表格,該表格由 DataGridView 中的發票項目填充。 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)來啟動。 應用程序的表單顯示,準備好供用戶互動。 輸入發票數據 在頂部的指定文本框中輸入客戶詳細信息,包括客戶姓名、地址、電子郵件和電話號碼。 通過填寫表單的“添加發票項目”區域中的“項目 ID”、“描述”、“數量”和“單價”字段來添加發票項目。 點擊“添加項目”將項目包含在發票清單中。 DataGridView 將更新顯示新項目,其詳細信息和計算出的總價。 重複此過程以將所有必要的項目添加到發票中。 “總金額”標籤將動態更新以反應列出的項目的累積總和。 生成 PDF 發票 當所有項目均已添加且客戶信息完整後,點擊“生成發票”。 應用程序將數據編譯為 HTML 格式,以 CSS 樣式化。 IronPDF 接手將 HTML 字符串轉換為 PDF 文檔。 它用 Chrome 引擎渲染,確保對現代網頁標準的高度保真。 查看生成的發票 在生成 PDF 之後,應用程序將 PDF 文件保存到指定位置,通常在與應用程序相同的目錄或用戶定義的路徑中。 成功訊息顯示以通知用戶 PDF 發票已成功保存。 用戶可以導航到已保存的位置查閱或分發發票。 輸出 PDF 輸出 PDF在頂部顯示客戶信息,接著是購買項目的詳細表,包括描述、數量和價格。 發票的總金額在文檔末尾列表,清楚地表明客戶需要支付的金額。 PDF 的設計簡潔且專業,利用代碼中的 CSS 確保發票不僅功能齊全而且外觀也美觀。 將 Windows Forms 項目轉換為可執行文件 在徹底測試您的 Windows Forms 應用程序並確保數據輸入、PDF 生成和輸出等所有功能正常運行後,下一階段是將您的項目打包為可執行(.exe)文件。 此轉換過程在 .NET 框架內流暢進行,確保您的應用程序準備好在 Windows 機器上安裝和使用。 以下是創建可執行文件的步驟: 構建應用程序: 轉到“Build”菜單並選擇“Build Solution”。 這將代碼編譯為組件並執行必要的優化。 定位可執行文件: 构建完成后,導航到項目目錄中的“bin\Debug\net8.0”文件夾。 在此處,您將找到 .exe 文件以及運行您的應用程序所需的其他任何依賴項。 測試可執行文件: 測試的好習慣是在不同的機器上運行 .exe 文件,以確認它能夠在開發環境之外正確運行。 準備分發: 對於分發,如果不需要其他依賴項,您可以直接分享 .exe 文件。 但是,為了更加專業的方式,請考慮使用 Visual Studio 中的安裝項目或第三方安裝包如 Inno Setup 或 WiX Toolset 創建安裝程序。 一個安裝程序可以管理安裝過程,創建快捷方式,並處理註冊到 Windows 註冊表等其他複雜功能(如有需要)。 通過遵循這些步驟,您的 Windows Forms 應用程序被壓縮到單個執行文件,準備好分享和使用。 此轉換標誌著開發過程的完成,從您開發機器上的一個項目過渡到可部署的軟件,可在眾多 Windows 環境中高效地分發和安裝。 結論 總之,使用 IronPDF 和 .NET 框架生成 PDF 發票的 Windows Forms 應用程序的開發展示了軟體開發原則的實際應用。 此項目不僅展示了 .NET 生態系統的多樣性和力量,還展示了開發人員如何集成像 IronPDF 這樣的第三方庫來擴展功能並滿足特定的業務需求。 通過遵循所述步驟,從設置用戶界面到實現 PDF 生成和將應用程序打包成可執行文件,開發人員可以創建一個功能強大且用戶友好的應用程序。 這個過程突顯了結合強健的程式設計框架和創新庫以解決現實世界問題的重要性,最終交付既有效又高效的產品。 IronPDF 慷慨地提供免費試用 PDF 生成功能供開發人員探索其特性並確定如何最好地滿足他們的需求。 一旦您體驗了其好處並準備好將 IronPDF 集成到生產環境中,許可證從可承擔的定價選項開始。 Once you've experienced the benefits and are ready to integrate IronPDF into your production environment, licenses start from affordable pricing options. 常見問題解答 怎樣在 C# 中將 HTML 轉換為 PDF? 您可以使用 IronPDF 的 RenderHtmlAsPdf 方法將 HTML 字符串轉換為 PDF。您還可以使用 RenderHtmlFileAsPdf 將 HTML 文件轉換為 PDF。 使用 .NET Core 進行跨平台開發的好處是什麼? .NET Core 允許您在多個平台上運行應用程序,如 Linux、macOS 和 Windows,這使其成為那些希望使用單一代碼庫接觸更廣泛受眾的開發者的多才多藝選擇。 如何從 Windows 表單應用程序生成 PDF? 使用 IronPDF,您可以通過在您的項目中集成該庫並利用其方法將表單數據或 HTML 內容轉換為 PDF 文檔來從 Windows 表單應用程序生成 PDF。 .NET 為什麼是一個理想的構建 Web 應用程序的框架? .NET,特別是 ASP.NET,提供了一個構建動態和可擴展 Web 應用程序的強大框架。它提供了內建的伺服器端腳本、身份驗證、數據處理等工具。 如何通過文檔生成功能增強我的 .NET 應用程序? 將像 IronPDF 這樣的庫集成到您的 .NET 應用程序中可以顯著增強其文檔生成功能,允許您在應用程序內直接創建、操縱和管理 PDF 文件。 .NET 可以用於移動應用程序開發嗎? 可以,.NET 支持通過 Xamarin 框架進行移動應用程序開發,這現在是 .NET MAUI 的一部分。這允許創建擁有本地性能的跨平台移動應用程序,在 iOS、Android 和 Windows 上運行。 通用語言運行時(CLR)在 .NET 中的重要性是什麼? 通用語言運行時(CLR)在 .NET 中至關重要,因為它通過將編譯代碼轉換為本地機器代碼來管理程序的執行,確保在不同操作系統之間的兼容性。 如何使用 NuGet 將 PDF 生成集成到我的 .NET 項目中? 您可以通過使用 NuGet 安裝像 IronPDF 這樣的庫來將 PDF 生成集成到您的 .NET 項目中。這使得在 Visual Studio 中添加 PDF 功能變得方便和簡單。 使用 Windows 表單創建 PDF 發票生成器的步驟有哪些? 過程包括設置一個 Windows 表單項目,設計界面,通過 NuGet 添加所需的庫,實現數據輸入和發票生成的邏輯,並使用 IronPDF 將發票細節轉換為 PDF。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Dotnet NuGet(對於開發者的運行原理)C# 模式匹配表達式(對於...