using MigraDoc.DocumentObjectModel; using MigraDoc.DocumentObjectModel.IO; using MigraDoc.DocumentObjectModel.Tables; using MigraDoc.Rendering; using PdfSharp.Pdf; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using WinFormsLibrary1.Configs.Table; namespace WinFormsLibrary1 { public partial class PdfWithTable : Component { public void CreatePdf(PdfWithTableConfig config) { config.CheckFields(); // Создание документа var document = new Document(); var section = document.AddSection(); // Установка заголовка var titleParagraph = section.AddParagraph(config.DocumentTitle); titleParagraph.Format.Alignment = ParagraphAlignment.Center; titleParagraph.Format.Font.Size = 16; titleParagraph.Format.Font.Bold = true; titleParagraph.Format.SpaceAfter = 20; // Создание таблицы var table = section.AddTable(); table.Borders.Width = 0.75; // Создание столбцов for (int i = 0; i < config.Data.Count + 2; i++) { var column = table.AddColumn(Unit.FromCentimeter(3)); // Ширину можно настроить column.Format.Alignment = ParagraphAlignment.Center; } // Создание заголовков for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++) { var row = table.AddRow(); row.Height = Unit.FromCentimeter(config.RowHeights[rowIndex]); // Высота строки foreach (Cell cell in row.Cells) { cell.VerticalAlignment = VerticalAlignment.Center; cell.Format.Alignment = ParagraphAlignment.Center; } } int rowNum = 0; foreach (var kvp in config.Headers) { string key = kvp.Key; List values = kvp.Value; if (values.Count == 0) { table.Rows[rowNum].Cells[0].AddParagraph(key); table.Rows[rowNum].Cells[0].MergeRight = 1; rowNum++; } else { table.Rows[rowNum].Cells[0].AddParagraph(key); table.Rows[rowNum].Cells[0].MergeDown = values.Count - 1; foreach (var value in values) { table.Rows[rowNum].Cells[1].AddParagraph(value); rowNum++; } } } for (int colIndex = 0; colIndex < config.Data.Count; colIndex++) { for (int rowIndex = 0; rowIndex < config.PropertiesPerRow.Count; rowIndex++) { Type type = typeof(T); PropertyInfo property = type.GetProperty(config.PropertiesPerRow[rowIndex]); if (property == null) { throw new ArgumentException($"Property with name {config.PropertiesPerRow[rowIndex]} doesn't exist in class {type.Name}"); } table.Rows[rowIndex].Cells[colIndex + 2].AddParagraph(property.GetValue(config.Data[colIndex]).ToString()); } } // Рендеринг документа в PDF var pdfRenderer = new PdfDocumentRenderer(true) { Document = document }; pdfRenderer.RenderDocument(); pdfRenderer.PdfDocument.Save(config.FileName); } } }