在 C# 中将数据从数据库添加到 PDF

数据库几乎无处不在,用于存储和管理数据。程序员的常见做法是从数据库中检索数据并将其加载到应用程序中。以编程方式生成 PDF 文件时,可能需要使用数据库中的数据填充文档。为了在 .NET 应用程序中实现这一点,本文展示了如何在 C# 中将数据从数据库添加到 PDF 文件。

C# .NET API 将数据从数据库添加到 PDF

我们将使用 Aspose.PDF for .NET 将数据库中的数据添加到 PDF 文件中。它是一种流行的 PDF 生成和操作 API,可让您无缝创建简单和复杂布局的 PDF 文件。您可以 下载 API 的二进制文件或使用 NuGet 安装它。

PM> Install-Package Aspose.PDF

在 C# 中将数据从数据库添加到 PDF

在大多数情况下,数据是从数据库表中提取到 DataTable 或 DataView 中的。因此,为了演示,我们将使用 DataTable 将数据添加到 PDF 文件中。为了使事情更简单,我们将在不使用数据库的情况下以编程方式创建和填充 DataTable。以下是使用 C# 将数据从数据库添加到 PDF 文件的步骤。

以下代码示例展示了如何在 C# 中将数据从数据库导入 PDF。

// 从数据库获取数据到DataTable
DataTable dt = new DataTable("Employee");
dt.Columns.Add("Employee_ID", typeof(Int32));
dt.Columns.Add("Employee_Name", typeof(string));
dt.Columns.Add("Gender", typeof(string));

// 以编程方式将 2 行添加到 DataTable 对象中
DataRow dr = dt.NewRow();
dr[0] = 1;
dr[1] = "John Smith";
dr[2] = "Male";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = 2;
dr[1] = "Mary Miller";
dr[2] = "Female";
dt.Rows.Add(dr);

// 创建文档实例
Document doc = new Document();
doc.Pages.Add();

// 初始化表的新实例
Aspose.Pdf.Table table = new Aspose.Pdf.Table();

// 设置表格的列宽
table.ColumnWidths = "40 100 100 100";

// 将表格边框颜色设置为 LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));

// 设置表格单元格的边框
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));

// 导入数据
table.ImportDataTable(dt, true, 0, 1, 3, 3);

// 将表格对象添加到输入文档的第一页
doc.Pages[1].Paragraphs.Add(table);

// 保存包含表格对象的更新文档
doc.Save("output.pdf");

以下是上述代码示例的输出。

在 C# 中将数据从数据库添加到 PDF

在实体框架中将数据从数据库添加到 PDF

如今,实体框架 (EF) 已被开发人员普遍使用。因此,扩展 Table 类以在 EF 中使用列表或分组数据填充 PDF 文档会很方便。以下是如何使用列表和分组数据填充 PDF 表的实现。在这两种方法中,表和数据都作为方法的参数传递。

public static class PdfHelper
{
    public static void ImportEntityList<TSource>(this Pdf.Table table, IList<TSource> data)
    {
        var headRow = table.Rows.Add();

        var props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in props)
        {
            headRow.Cells.Add(prop.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute dd ? dd.Name : prop.Name);
        }

        foreach (var item in data)
        {
            // 向表中添加行
            var row = table.Rows.Add();
            // 添加表格单元格
            foreach (var t in props)
            {
                var dataItem = t.GetValue(item, null);
                if (t.GetCustomAttribute(typeof(DataTypeAttribute)) is DataTypeAttribute dataType)
                    switch (dataType.DataType)
                    {

                        case DataType.Currency:
                            row.Cells.Add(string.Format("{0:C}", dataItem));
                            break;
                        case DataType.Date:
                            var dateTime = (DateTime)dataItem;
                            if (t.GetCustomAttribute(typeof(DisplayFormatAttribute)) is DisplayFormatAttribute df)
                            {
                                row.Cells.Add(string.IsNullOrEmpty(df.DataFormatString)
                                    ? dateTime.ToShortDateString()
                                    : string.Format(df.DataFormatString, dateTime));
                            }
                            break;
                        default:
                            row.Cells.Add(dataItem.ToString());
                            break;
                    }
                else
                {
                    row.Cells.Add(dataItem.ToString());
                }
            }
        }
    }
    public static void ImportGroupedData<TKey,TValue>(this Pdf.Table table, IEnumerable<Models.GroupViewModel<TKey, TValue>> groupedData)
    {
        var headRow = table.Rows.Add();           
        var props = typeof(TValue).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (var prop in props)
        {
           headRow.Cells.Add(prop.GetCustomAttribute(typeof(DisplayAttribute)) is DisplayAttribute dd ? dd.Name : prop.Name);               
        }

        foreach (var group in groupedData)
        {
            // 将组行添加到表格
            var row = table.Rows.Add();
            var cell = row.Cells.Add(group.Key.ToString());
            cell.ColSpan = props.Length;
            cell.BackgroundColor = Pdf.Color.DarkGray;
            cell.DefaultCellTextState.ForegroundColor = Pdf.Color.White;

            foreach (var item in group.Values)
            {
                // 向表中添加数据行
                var dataRow = table.Rows.Add();
                // 添加单元格
                foreach (var t in props)
                {
                    var dataItem = t.GetValue(item, null);

                    if (t.GetCustomAttribute(typeof(DataTypeAttribute)) is DataTypeAttribute dataType)
                        switch (dataType.DataType)
                        {
                            case DataType.Currency:
                                dataRow.Cells.Add(string.Format("{0:C}", dataItem));
                                break;
                            case DataType.Date:
                                var dateTime = (DateTime)dataItem;
                                if (t.GetCustomAttribute(typeof(DisplayFormatAttribute)) is DisplayFormatAttribute df)
                                {
                                    dataRow.Cells.Add(string.IsNullOrEmpty(df.DataFormatString)
                                        ? dateTime.ToShortDateString()
                                        : string.Format(df.DataFormatString, dateTime));
                                }
                                break;
                            default:
                                dataRow.Cells.Add(dataItem.ToString());
                                break;
                        }
                    else
                    {
                        dataRow.Cells.Add(dataItem.ToString());
                    }
                }
            }
        }
    }
}
public class GroupViewModel<K,T>
{
    public K Key;
    public IEnumerable<T> Values;
}

获得免费许可证

您可以获得免费的临时许可证 以便在没有评估限制的情况下使用 Aspose.PDF for .NET。

结论

在本文中,您学习了如何使用 C# 将数据库中的数据添加到 PDF 文件中。您已经了解了如何将数据从 DataTable 导入 PDF 文件中的表格。此外,我们还介绍了使用实体框架将数据导入 PDF 的实现。此外,您可以使用 文档 探索更多关于 C# PDF API 的信息。如果您有任何问题或疑问,可以通过我们的 论坛 与我们联系。

也可以看看