Thêm dữ liệu từ cơ sở dữ liệu sang PDF trong C#

Cơ sở dữ liệu hầu như ở khắp mọi nơi để lưu trữ và quản lý dữ liệu. Một thực tế phổ biến của các lập trình viên là lấy dữ liệu từ cơ sở dữ liệu và tải nó vào các ứng dụng. Khi tạo tệp PDF theo chương trình, người ta có thể cần đưa tài liệu vào dữ liệu trong cơ sở dữ liệu. Để thực hiện điều đó trong các ứng dụng .NET, bài viết này hướng dẫn cách thêm dữ liệu từ cơ sở dữ liệu vào tệp PDF trong C#.

C# .NET API để thêm dữ liệu từ cơ sở dữ liệu sang PDF

Chúng tôi sẽ sử dụng Aspose.PDF for .NET để thêm dữ liệu từ cơ sở dữ liệu vào tệp PDF. Đây là một API thao tác và tạo PDF phổ biến cho phép bạn tạo các tệp PDF có bố cục đơn giản và phức tạp một cách liền mạch. Bạn có thể tải xuống mã nhị phân của API hoặc cài đặt nó bằng NuGet.

PM> Install-Package Aspose.PDF

Thêm dữ liệu từ cơ sở dữ liệu sang PDF trong C#

Trong hầu hết các trường hợp, dữ liệu được tìm nạp từ bảng cơ sở dữ liệu vào DataTable hoặc DataView. Do đó, để trình diễn, chúng tôi sẽ sử dụng DataTable để thêm dữ liệu vào tệp PDF. Để giữ cho mọi thứ đơn giản hơn, chúng tôi sẽ tạo và điền DataTable theo lập trình mà không cần sử dụng cơ sở dữ liệu. Sau đây là các bước để thêm dữ liệu vào tệp PDF từ cơ sở dữ liệu trong C#.

Mẫu mã sau đây cho thấy cách nhập dữ liệu từ cơ sở dữ liệu sang PDF trong C#.

// Lấy dữ liệu từ cơ sở dữ liệu vào 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));

// Thêm 2 hàng vào đối tượng DataTable theo lập trình
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);

// Tạo phiên bản tài liệu
Document doc = new Document();
doc.Pages.Add();

// Khởi tạo một phiên bản mới của Bảng
Aspose.Pdf.Table table = new Aspose.Pdf.Table();

// Đặt chiều rộng cột của bảng
table.ColumnWidths = "40 100 100 100";

// Đặt màu đường viền bảng là LightGray
table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));

// Đặt đường viền cho các ô trong bảng
table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));

// Nhập dữ liệu
table.ImportDataTable(dt, true, 0, 1, 3, 3);

// Thêm đối tượng bảng vào trang đầu tiên của tài liệu đầu vào
doc.Pages[1].Paragraphs.Add(table);

// Lưu tài liệu đã cập nhật có chứa đối tượng bảng
doc.Save("output.pdf");

Sau đây là kết quả của mẫu mã trên.

Thêm dữ liệu từ cơ sở dữ liệu sang PDF trong C#

Thêm dữ liệu từ cơ sở dữ liệu sang PDF trong Entity Framework

Ngày nay, Entity Framework (EF) đang được các nhà phát triển sử dụng phổ biến. Do đó, sẽ rất hữu ích nếu mở rộng lớp Bảng để điền các tài liệu PDF với danh sách hoặc dữ liệu được nhóm trong EF. Sau đây là cách thực hiện cách điền bảng PDF bằng danh sách và dữ liệu được nhóm. Trong cả hai phương thức, Bảng và dữ liệu được truyền dưới dạng các đối số của phương thức.

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)
        {
            // Thêm hàng vào bảng
            var row = table.Rows.Add();
            // Thêm các ô trong bảng
            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)
        {
            // Thêm hàng nhóm vào bảng
            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)
            {
                // Thêm hàng dữ liệu vào bảng
                var dataRow = table.Rows.Add();
                // Thêm ô
                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;
}

Nhận giấy phép miễn phí

Bạn có thể nhận giấy phép tạm thời miễn phí để sử dụng Aspose.PDF for .NET mà không có giới hạn đánh giá.

Sự kết luận

Trong bài này, bạn đã học cách thêm dữ liệu từ cơ sở dữ liệu vào tệp PDF trong C#. Bạn đã thấy cách nhập dữ liệu từ DataTable vào bảng trong tệp PDF. Ngoài ra, chúng tôi đã đề cập đến việc triển khai nhập dữ liệu sang PDF bằng Entity Framework. Bên cạnh đó, bạn có thể khám phá thêm về C# PDF API bằng cách sử dụng tài liệu. Trong trường hợp bạn có bất kỳ câu hỏi hoặc thắc mắc nào, bạn có thể liên hệ với chúng tôi qua diễn đàn của chúng tôi.

Xem thêm