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); InitializeComponent(); } public void GeneratePDFWithHead(PDFTableSettings 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(); section.AddParagraph(settings.DocumentTitle, "Heading1"); 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 columnIndex = 0; columnIndex < settings.Columns.Count; columnIndex++) { var (headerTitle, _, _, _) = settings.Columns[columnIndex]; headerRow.Cells[columnIndex].AddParagraph(headerTitle); headerRow.Cells[columnIndex].Format.Font.Bold = true; headerRow.Cells[columnIndex].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); } } }