.NET 帮助

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

.NET Framework 软件开发代表了一种由微软支持的强大而多功能的框架,使 .NET 开发人员能够创建跨多个平台、操作系统和设备的健壮且高质量的应用程序。 该软件开发框架设计全面,提供工具、库和 API,软件开发人员可以使用这些工具、库和 API 在 .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 应用程序在从主要移动操作系统到 Windows 网络服务器等各种平台上无缝运行。

跨平台框架

.NET Core 作为一个跨平台框架出现,允许 .NET 应用程序在 Linux、macOS 和 Windows 上运行。 .NET的这种适应性使其成为开发人员的首选,他们希望通过不同的设备和平台接触到更多的受众。 有了 .NET Core,可以在任何支持的操作系统上开发和部署应用程序,在广泛的 .NET 社区的支持下,增强了 .NET 软件开发的覆盖面和灵活性。

集成开发环境 (IDE)

Visual Studio 是用于 .NET 开发的首选集成开发环境 (IDE)。 它为开发人员提供了代码编写、调试和部署 .NET 应用程序的强大工具。 Visual Studio 支持各种编程语言,并为构建 Web、桌面和移动应用程序提供了大量功能,是 .NET 开发人员不可或缺的工具。

使用 .NET 构建应用程序

在 .NET 平台上创建应用程序需要利用该框架提供的各种工具、库和编程语言,如 Visual Basic,从而展示其全面的生态系统。 这种多功能性使软件开发人员能够构建各种类型的 .NET 应用程序,从网络和桌面应用程序到基于云和移动的解决方案。

使用 ASP.NET 进行网络开发

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

桌面应用程序开发

.NET 提供了创建桌面应用程序的两种主要方法:Windows 窗体和 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 Framework 中人工智能的力量。

使用 IronPDF 加强 .NET 软件开发

.NET 软件开发(开发人员如何工作):图 1 - IronPDF

在充满活力的 .NET 软件开发生态系统中,在应用程序中直接生成、处理和管理 PDF 文档的能力具有显著优势。 IronPDF 是专为 .NET 开发人员设计的强大库,可无缝集成到该环境中,为从 .NET 应用程序(包括使用 Windows Forms 构建的应用程序)创建 PDF 提供了一种高效的方法。

IronPDF 在 .NET 应用程序中的作用

IronPDF 作为 .NET 生态系统灵活性和强大功能的证明,为开发人员提供了一个直观的 API,可以从 HTML、图像、文本,甚至 ASP.NET 网页生成 PDF 文档。 在需要创建动态文档的场景中,例如在桌面应用程序中生成发票、报告或个性化文档时,这种能力尤其有用。

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

一个用于生成发票的 Windows Form 应用程序体现了 .NET 软件开发与 IronPDF 结合的实际应用。 该应用程序允许用户输入客户信息、采购项目和价格等详细信息,然后一键生成专业的 PDF 发票。

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

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

.NET 软件开发(它如何为开发者工作):图 2 - 发票生成器 Windows Form 输出

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

客户信息部分

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

添加发票项目

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

发票项目列表

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

发票业务

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

该用户界面不仅功能强大,而且直观,使用户能够轻松地与应用程序进行交互,而无需花费大量时间学习。 它旨在包含生成发票的所有必要信息,同时提供从数据录入到 PDF 创建的清晰而直接的路径。

将IronPDF添加到您的项目中

项目完成后,下一步就是将 IronPDF 加入其中。 这是通过 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
$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);
     }
     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
$vbLabelText   $csharpLabel

生成 PDF 发票

单击“生成发票”时,应用程序会执行btnInvoice_Click事件处理程序,在其中使用StringBuilder构建HTML字符串。 该字符串包括客户的详细信息和一个由 DataGridView 中的发票项目填充的样式 HTML 表格。 然后,IronPdf 的渲染器会将 HTML 转换成 PDF 文档,并保存到指定路径。 应用程序会向用户发送一条消息,确认发票创建成功。

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

运行应用程序和生成发票

一旦开发出 Windows 窗体应用程序并集成了 IronPDF 库,运行应用程序并生成 PDF 发票就是一个简单明了的过程。 用户与应用程序的用户界面进行交互,输入数据并生成所需的输出。 以下是典型的翻译过程:

启动应用程序

通过在 Visual Studio 中运行应用程序或直接从 Windows 环境执行已编译的可执行文件(.exe)来启动应用程序。 显示应用程序的表单,以便用户进行交互。

输入发票数据

在指定的文本框中输入客户详细信息,包括客户的姓名、地址、电子邮件和电话号码。 通过填写表格 "添加发票项目 "部分的 "项目 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 Forms应用程序并确保数据输入、PDF生成和输出等所有功能无缝运行后,下一阶段是将您的项目打包为可执行文件(.exe)。这种转换过程在.NET框架中得到简化,确保您的应用程序可以安装并在Windows机器上使用。

以下是创建可执行文件的步骤:

  1. 构建应用程序: 进入“构建”菜单并选择“构建解决方案”。这会将代码编译成程序集并执行必要的优化。

    .NET 软件开发(开发人员如何工作):图 7 - 构建解决方案

  2. 定位可执行文件: 构建完成后,导航到项目目录中的 'bin\Debug\net8.0' 文件夹。 在这里,您可以找到 .exe 文件以及运行应用程序所需的任何其他依赖项。

    .NET 软件开发(开发人员如何操作):图 8 - 可执行文件位置

  3. 测试可执行文件:在另一台计算机上运行 .exe 文件是一个很好的做法,以确认它在您的开发环境之外正常运行。

  4. 准备分发:对于分发,如果不需要额外的依赖项,您可以直接共享.exe文件。 不过,如果想采用更专业的方法,可以考虑使用 Visual Studio 中的设置项目或 Inno Setup 或 WiX Toolset 等第三方安装包创建安装程序。 安装程序可以管理安装过程、创建快捷方式并处理其他复杂问题,例如在需要时向 Windows 注册表注册。

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

结论

.NET 软件开发(开发人员如何运作):图 9 - 许可

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

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

IronPDF为开发人员慷慨地提供PDF生成功能的免费试用,以便探索其功能并确定其最适合他们需求的方式。 一旦您体验到 IronPDF 带来的好处,并准备将其集成到您的生产环境中,许可证就可以从经济实惠的定价选项开始。

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
Dotnet NuGet(对开发人员的工作原理)
下一步 >
C# 模式匹配表达式(开发者如何使用)