PIbd-31_Danilov_V_V_COP-30/Components/NonVisual/HeaderedTablePDF.cs
2024-11-02 18:51:07 +04:00

99 lines
3.0 KiB
C#

using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Components.SaveToPdfHelpers;
namespace Components.NonVisual
{
public partial class HeaderedTablePDF : Component
{
public HeaderedTablePDF()
{
InitializeComponent();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
public HeaderedTablePDF(IContainer container)
{
container.Add(this);
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
InitializeComponent();
}
public void GeneratePDFWithHead<T>(PDFTableSettings<T> settings)
{
if (settings == null ||
string.IsNullOrEmpty(settings.FilePath) ||
string.IsNullOrEmpty(settings.DocumentTitle) ||
settings.Columns == null || settings.Columns.Count == 0 ||
settings.DataList == null)
throw new ArgumentException("Заполнены не все необходимые данные для генерации документа.");
Document document = new Document();
Section section = document.AddSection();
Paragraph titleParagraph = section.AddParagraph(settings.DocumentTitle, "Heading1");
titleParagraph.Format.Font.Bold = true;
Table table = new Table();
table.Borders.Width = 0.75;
// столбцы
foreach (var (_, width, _, _) in settings.Columns)
{
Column column = table.AddColumn(Unit.FromCentimeter(width));
column.Format.Alignment = ParagraphAlignment.Center;
}
// заголовки
Row headerRow = table.AddRow();
headerRow.Height = Unit.FromCentimeter(settings.HeaderRowHeight);
for (int i = 0; i < settings.Columns.Count; i++)
{
var (headerTitle, _, _, _) = settings.Columns[i];
headerRow.Cells[i].AddParagraph(headerTitle);
headerRow.Cells[i].Format.Font.Bold = true;
headerRow.Cells[i].Format.Alignment = ParagraphAlignment.Center;
}
// данные
foreach (var dataItem in settings.DataList)
{
Row row = table.AddRow();
row.Height = Unit.FromCentimeter(settings.DataRowHeight);
for (int columnIndex = 0; columnIndex < settings.Columns.Count; columnIndex++)
{
var (_, _, propertyName, _) = settings.Columns[columnIndex];
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo == null)
throw new ArgumentException($"Свойство {propertyName} не найдено в классе {typeof(T).Name}.");
object value = propertyInfo.GetValue(dataItem);
if (columnIndex == 0)
{
row.Cells[columnIndex].Format.Font.Bold = true;
}
row.Cells[columnIndex].AddParagraph(value != null ? value.ToString() : "");
}
}
section.Add(table);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document };
renderer.RenderDocument();
renderer.Save(settings.FilePath);
}
}
}