.NET 帮助

.NET 软件开发(如何为开发人员工作)

发布 2024年三月26日
分享:

.NET Framework 软件开发 .NET是微软支持的一个功能强大、用途广泛的框架,它使.NET开发人员能够创建跨越各种平台、操作系统和设备的强大、高质量的应用程序。该软件开发框架设计全面,提供工具、库和应用程序接口,软件开发人员可利用这些工具、库和应用程序接口在 .NET 平台上高效地构建网络、桌面和移动应用程序。

.NET开发支持多种编程语言(包括C#、Visual Basic和F#),为开发人员提供了灵活性,确保他们可以使用自己喜欢的语言工作,同时受益于.NET Core生态系统的丰富功能。在本教程中,我们将看到 IronPDF 演示.NET 开发如何解决实际问题。

了解.NET软件开发的生态系统

.NET生态系统是.NET的一个重要实现方式,它是一个广泛的、包罗万象的平台,包括各种组件和技术,旨在促进跨不同操作系统的应用程序开发。在其核心部分,.NET Framework 和 .NET Core 是运行 .NET 应用程序的主要引擎,提供了一个通用语言运行时 (CLR) 它管理代码的执行,并提供内存管理、类型安全、异常处理等服务。

通用语言运行时 (CLR)

CLR 是 .NET 体系结构的一个重要元素,它使 .NET 代码能够在不同的操作系统上执行。它编译通用中间语言 (CIL) .NET应用程序可以将.NET代码转换成主机可以直接执行的本地机器代码。这一过程可确保 .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),这展示了其全面的生态系统。这种多功能性使软件开发人员能够构建各种类型的 .NET 应用程序,从网络和桌面应用程序到基于云的移动解决方案。

使用 ASP.NET 进行网页开发

ASP.NET 是 .NET 框架的重要组成部分,专门用于构建动态网页和应用程序。它允许开发人员创建可处理大量流量的反应灵敏、可扩展的网络应用程序。ASP.NET Core 是 ASP.NET 的开源版本,它为构建跨平台网络应用程序带来了更多的功能,使在 Windows、Linux 和 macOS 上开发和部署网络应用程序成为可能。

桌面应用程序的开发

.NET 为创建桌面应用程序提供了两种主要方法:Windows 窗体和 Windows Presentation Foundation (WPF).Windows Forms 提供了创建具有丰富图形用户界面的桌面应用程序的直接方法,而 WPF 则使用 XAML (可扩展应用标记语言) 以开发具有高级图形和动画的视觉吸引力强的用户界面。

移动应用开发

在移动开发方面,.NET 通过 Xamarin 框架将其触角延伸到主要移动操作系统,Xamarin 框架现已集成到 .NET 中,成为 .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),使他们能够在.NET 应用程序中使用 IronPDF。 从 HTM 生成 PDF 文档 这种功能在需要创建动态文档(如在桌面应用程序中生成发票、报告或个性化文档)的情况下特别有用。这种功能在需要动态文档创建的情况下特别有用,例如在桌面应用程序中生成发票、报告或个性化文档。

使用 IronPDF 创建 Windows 表单发票生成器

一个用于生成发票的 Windows 窗体应用程序是.NET 软件开发与 IronPDF 相结合的实际应用的典范。该应用程序允许用户输入客户信息、采购项目和价格等详细信息,然后只需点击一下即可生成专业的 PDF 发票。

设置 Windows 窗体项目并设计用户界面

首先在 Visual Studio 中创建一个新的 Windows 窗体项目。这是您的基础,您将在此为您的发票生成器设计用户界面。设计表单时要包含必要的客户和项目详细信息输入字段,以及生成 PDF 的按钮。这就是我们的发票生成器用户界面:

.NET软件开发(如何为开发人员工作):图 2 - 发票生成器 Windows 窗体输出

Windows 窗体应用程序的用户界面经过精心设计,确保易于使用且功能强大。名为 "发票生成器 "的主窗口被划分为不同的部分,为用户提供无缝体验。

客户信息科

表单顶部包括 "客户姓名"、"客户地址"、"客户电子邮件 "和 "客户电话号码 "字段。该区域用于捕捉重要的客户详细信息,这些信息将在生成的发票上占据显著位置。

添加发票项目

在客户信息下方,有一个标有 "添加发票项目 "的区域。在这里,用户可以输入单个项目的详细信息,如 "项目 ID"、"描述"、"数量 "和 "单价"。在这些字段旁边有一个 "添加项目 "按钮,用户可以将输入的项目添加到下面的发票列表中。

发票项目清单

表格的中心部分是 "发票信息 "部分,显示一个表格,输入的项目会在添加时显示出来。表格列包括 "项目 ID"、"描述"、"数量"、"单价 "和 "总价",最后一列根据数量和单价自动计算。名为 "选择日期 "的日期选择器允许用户指定发票日期,增加了文档的特殊性。

发票业务

在表单底部,一个标签显示 "总金额",并随着项目的添加或删除而动态更新。这可确保用户实时了解发票的总价值。此外,"生成发票 "按钮会提示应用程序使用 IronPDF 库,根据输入的数据创建 PDF 版本的发票。

该用户界面不仅功能强大,而且直观易用,用户可以轻松地与应用程序进行交互,而无需花费大量时间学习。它的设计可容纳生成发票所需的所有信息,同时提供从数据输入到 PDF 创建的清晰而直接的路径。

将 IronPDF 添加到您的项目中

项目设置完成后,下一步就是将 IronPDF 加入其中。这是通过 NuGet(Visual Studio 的集成 NuGet 包管理器)完成的,它可以让你毫不费力地将 IronPDF 添加到项目中。编写并运行以下命令

Install-Package IronPdf

该命令将安装 IronPDF,并可在我们的项目中使用。

.NET软件开发(如何为开发人员工作):图 3 - 安装 IronPDF

实现发票生成

Windows 窗体应用程序的核心是处理用户输入、将数据组织成结构化格式并生成有形文档(本例中为 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。该方法将输入的值添加到数据网格视图的新行中,计算项目的总价并更新表单底部显示的发票总金额。

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 窗体应用程序并集成了 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 窗体项目转换为可执行文件

在彻底测试 Windows 窗体应用程序并确保数据输入、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 注册表注册。

按照这些步骤,您的 Windows 窗体应用程序就浓缩成了一个可执行文件,随时可以共享和使用。这一转换标志着开发过程达到了顶峰,从开发机器上的一个项目过渡到了可部署软件,可在多种 Windows 环境中有效分发和安装。

结论

.NET软件开发(如何为开发人员服务):图 9 - 许可证

总之,使用 IronPDF 和 .NET Framework 开发用于生成 PDF 发票的 Windows 窗体应用程序是软件开发原则的实际应用范例。该项目不仅展示了 .NET 生态系统的多功能性和强大功能,还演示了开发人员如何集成 IronPDF 等第三方库来扩展功能和满足特定业务需求。

按照概述的步骤,从设置用户界面到实现 PDF 生成并将应用程序打包为可执行文件,开发人员可以创建一个功能强大、用户友好的应用程序。这一过程凸显了将强大的编程框架与创新库相结合以解决实际问题的重要性,最终交付的产品既有效又高效。

IronPDF 慷慨地提供了 免费试用 让开发人员探索其功能,并确定如何最大限度地满足他们的需求。一旦您体验到 IronPDF 的优势并准备将其集成到您的生产环境中,许可证将从 $749 起。

< 前一页
Dotnet NuGet(对开发人员的工作原理)
下一步 >
C# 模式匹配表达式(开发者如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >