сдано

This commit is contained in:
Алексей Тихоненков 2024-10-03 15:34:22 +04:00
parent 4b23ec76f2
commit 989d867eda
7 changed files with 47 additions and 71 deletions

View File

@ -15,6 +15,7 @@ namespace FormLibrary
public ComponentHistogramToPdf() public ComponentHistogramToPdf()
{ {
InitializeComponent(); InitializeComponent();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
} }
public ComponentHistogramToPdf(IContainer container) public ComponentHistogramToPdf(IContainer container)
@ -23,7 +24,7 @@ namespace FormLibrary
InitializeComponent(); InitializeComponent();
} }
public void CreateHistogramPdf(string filePath, string documentTitle, string chartTitle, LegendPositions legendPosition, List<ChartData> chartData) public void CreateHistogramPdf(string filePath, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartData> chartData)
{ {
if (string.IsNullOrEmpty(filePath)) if (string.IsNullOrEmpty(filePath))
throw new ArgumentException("Путь к файлу не может быть пустым."); throw new ArgumentException("Путь к файлу не может быть пустым.");
@ -84,31 +85,17 @@ namespace FormLibrary
} }
//добавление легенды //добавление легенды
private void AddLegend(PlotModel plotModel, LegendPositions legendPosition) private void AddLegend(PlotModel plotModel, LegendPosition legendPosition)
{ {
// Создание легенды // Создание легенды
var legend = new OxyPlot.Legends.Legend var legend = new OxyPlot.Legends.Legend
{ {
LegendPlacement = LegendPlacement.Outside, LegendPlacement = LegendPlacement.Outside,
LegendPosition = ConvertLegendPosition(legendPosition), LegendPosition = legendPosition,
LegendOrientation = LegendOrientation.Vertical LegendOrientation = LegendOrientation.Vertical
}; };
plotModel.Legends.Add(legend); plotModel.Legends.Add(legend);
} }
// конвертация позиции легенды
private OxyPlot.Legends.LegendPosition ConvertLegendPosition(LegendPositions legendPosition)
{
return legendPosition switch
{
LegendPositions.Top => OxyPlot.Legends.LegendPosition.TopCenter,
LegendPositions.Bottom => OxyPlot.Legends.LegendPosition.BottomCenter,
LegendPositions.Left => OxyPlot.Legends.LegendPosition.LeftTop,
LegendPositions.Right => OxyPlot.Legends.LegendPosition.RightTop,
_ => OxyPlot.Legends.LegendPosition.TopCenter, // Положение по умолчанию
};
}
} }
} }

View File

@ -10,12 +10,10 @@ namespace FormLibrary.HelperClasses
{ {
public string FilePath { get; set; } public string FilePath { get; set; }
public string DocumentTitle { get; set; } public string DocumentTitle { get; set; }
public List<string> HeaderTitles { get; set; } public List<(string HeaderTitle, float Width, string PropertyName, int ColumnIndex)> Columns { get; set; }
public List<float> ColumnWidths { get; set; }
public float HeaderRowHeight { get; set; } public float HeaderRowHeight { get; set; }
public float DataRowHeight { get; set; } public float DataRowHeight { get; set; }
public List<T> DataList { get; set; } public List<T> DataList { get; set; }
public Dictionary<int, string> ColumnPropertyMappings { get; set; }
} }
} }

View File

@ -8,6 +8,7 @@ namespace FormLibrary.HelperClasses
{ {
public class Student public class Student
{ {
public int Number { get; set; }
public string Group { get; set; } public string Group { get; set; }
public string FullName { get; set; } public string FullName { get; set; }
public int Course { get; set; } public int Course { get; set; }

View File

@ -32,15 +32,10 @@ namespace FormLibrary
if (settings == null || if (settings == null ||
string.IsNullOrEmpty(settings.FilePath) || string.IsNullOrEmpty(settings.FilePath) ||
string.IsNullOrEmpty(settings.DocumentTitle) || string.IsNullOrEmpty(settings.DocumentTitle) ||
settings.HeaderTitles == null || settings.HeaderTitles.Count == 0 || settings.Columns == null || settings.Columns.Count == 0 ||
settings.ColumnWidths == null || settings.DataList == null || settings.DataList == null)
settings.ColumnPropertyMappings == null)
throw new ArgumentException("Заполнены не все необходимые данные для генерации документа."); throw new ArgumentException("Заполнены не все необходимые данные для генерации документа.");
if (settings.HeaderTitles.Count != settings.ColumnWidths.Count)
throw new ArgumentException("Количество заголовков должно совпадать с количеством ширин столбцов.");
Document document = new Document(); Document document = new Document();
Section section = document.AddSection(); Section section = document.AddSection();
section.AddParagraph(settings.DocumentTitle, "Heading1"); section.AddParagraph(settings.DocumentTitle, "Heading1");
@ -49,20 +44,22 @@ namespace FormLibrary
table.Borders.Width = 0.75; table.Borders.Width = 0.75;
// столбцы // столбцы
for (int i = 0; i < settings.ColumnWidths.Count; i++) foreach (var (_, width, _, _) in settings.Columns)
{ {
Column column = table.AddColumn(Unit.FromCentimeter(settings.ColumnWidths[i])); Column column = table.AddColumn(Unit.FromCentimeter(width));
column.Format.Alignment = ParagraphAlignment.Center; column.Format.Alignment = ParagraphAlignment.Center;
} }
// заголовки // заголовки
Row headerRow = table.AddRow(); Row headerRow = table.AddRow();
headerRow.Height = Unit.FromCentimeter(settings.HeaderRowHeight); headerRow.Height = Unit.FromCentimeter(settings.HeaderRowHeight);
for (int i = 0; i < settings.HeaderTitles.Count; i++)
for (int columnIndex = 0; columnIndex < settings.Columns.Count; columnIndex++)
{ {
headerRow.Cells[i].AddParagraph(settings.HeaderTitles[i]); var (headerTitle, _, _, _) = settings.Columns[columnIndex];
headerRow.Cells[i].Format.Font.Bold = true; headerRow.Cells[columnIndex].AddParagraph(headerTitle);
headerRow.Cells[i].Format.Alignment = ParagraphAlignment.Center; headerRow.Cells[columnIndex].Format.Font.Bold = true;
headerRow.Cells[columnIndex].Format.Alignment = ParagraphAlignment.Center;
} }
// данные // данные
@ -71,14 +68,20 @@ namespace FormLibrary
Row row = table.AddRow(); Row row = table.AddRow();
row.Height = Unit.FromCentimeter(settings.DataRowHeight); row.Height = Unit.FromCentimeter(settings.DataRowHeight);
foreach (var columnMapping in settings.ColumnPropertyMappings) for (int columnIndex = 0; columnIndex < settings.Columns.Count; columnIndex++)
{ {
PropertyInfo propertyInfo = typeof(T).GetProperty(columnMapping.Value); var (_, _, propertyName, _) = settings.Columns[columnIndex];
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo == null) if (propertyInfo == null)
throw new ArgumentException($"Свойство {columnMapping.Value} не найдено в классе {typeof(T).Name}."); throw new ArgumentException($"Свойство {propertyName} не найдено в классе {typeof(T).Name}.");
object value = propertyInfo.GetValue(dataItem); object value = propertyInfo.GetValue(dataItem);
row.Cells[columnMapping.Key].AddParagraph(value != null ? value.ToString() : ""); if (columnIndex == 0)
{
row.Cells[columnIndex].Format.Font.Bold = true;
}
row.Cells[columnIndex].AddParagraph(value != null ? value.ToString() : "");
} }
} }

View File

@ -44,7 +44,6 @@
button8 = new Button(); button8 = new Button();
pdfTableCustom1 = new FormLibrary.PDFTableCustom(components); pdfTableCustom1 = new FormLibrary.PDFTableCustom(components);
button9 = new Button(); button9 = new Button();
button10 = new Button();
button11 = new Button(); button11 = new Button();
componentHistogramToPdf1 = new FormLibrary.ComponentHistogramToPdf(components); componentHistogramToPdf1 = new FormLibrary.ComponentHistogramToPdf(components);
SuspendLayout(); SuspendLayout();
@ -168,20 +167,13 @@
button9.UseVisualStyleBackColor = true; button9.UseVisualStyleBackColor = true;
button9.Click += btnGeneratePDF_Click; button9.Click += btnGeneratePDF_Click;
// //
// button10
//
button10.Location = new Point(0, 0);
button10.Name = "button10";
button10.Size = new Size(75, 23);
button10.TabIndex = 0;
//
// button11 // button11
// //
button11.Location = new Point(347, 481); button11.Location = new Point(347, 481);
button11.Name = "button11"; button11.Name = "button11";
button11.Size = new Size(139, 23); button11.Size = new Size(139, 23);
button11.TabIndex = 13; button11.TabIndex = 13;
button11.Text = "Create customPDF"; button11.Text = "Create Histogram PDF";
button11.UseVisualStyleBackColor = true; button11.UseVisualStyleBackColor = true;
button11.Click += btnGenerateHistogrammPdf_Click; button11.Click += btnGenerateHistogrammPdf_Click;
// //
@ -191,7 +183,6 @@
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(944, 625); ClientSize = new Size(944, 625);
Controls.Add(button11); Controls.Add(button11);
Controls.Add(button10);
Controls.Add(button9); Controls.Add(button9);
Controls.Add(button8); Controls.Add(button8);
Controls.Add(button7); Controls.Add(button7);
@ -228,7 +219,6 @@
private Button button8; private Button button8;
private FormLibrary.PDFTableCustom pdfTableCustom1; private FormLibrary.PDFTableCustom pdfTableCustom1;
private Button button9; private Button button9;
private Button button10;
private Button button11; private Button button11;
private FormLibrary.ComponentHistogramToPdf componentHistogramToPdf1; private FormLibrary.ComponentHistogramToPdf componentHistogramToPdf1;
} }

View File

@ -12,6 +12,7 @@ using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
using System.Windows.Forms.VisualStyles; using System.Windows.Forms.VisualStyles;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Header; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Header;
using OxyPlot.Legends;
namespace Forms namespace Forms
{ {
@ -131,7 +132,7 @@ namespace Forms
try try
{ {
var pdfData = new PdfDocumentData( var pdfData = new PdfDocumentData(
"G:\\Отчет1.pdf", "E:\\Отчет1.pdf",
"Название документа", "Название документа",
new List<string[,]> new List<string[,]>
{ {
@ -159,27 +160,25 @@ namespace Forms
} }
private void btnGeneratePDF_Click(object sender, EventArgs e) private void btnGeneratePDF_Click(object sender, EventArgs e)
{ {
// Создание объекта настроек
var settings = new PDFTableSettings<Student> var settings = new PDFTableSettings<Student>
{ {
FilePath = "G:\\Отчет2.pdf", FilePath = "E:\\Отчет2.pdf",
DocumentTitle = "Отчет по студентам", DocumentTitle = "Отчет по студентам",
HeaderTitles = new List<string> { "Группа", "ФИО", "Курс" },
ColumnWidths = new List<float> { 4.0f, 6.0f, 2.0f },
HeaderRowHeight = 1.0f, HeaderRowHeight = 1.0f,
DataRowHeight = 1.0f, DataRowHeight = 1.0f,
DataList = new List<Student> DataList = new List<Student>
{ {
new Student { Group = "Пибд-33", FullName = "Иван Иванов", Course = 3 }, new Student { Number = 1, Group = "Пибд-33", FullName = "Иван Иванов", Course = 3 },
new Student { Group = "Пибд-33", FullName = "Петр Петров", Course = 2 }, new Student { Number = 2, Group = "Пибд-33", FullName = "Петр Петров", Course = 2 },
new Student { Group = "Пибд-34", FullName = "Алексей Сидоров", Course = 4 } new Student { Number = 3, Group = "Пибд-34", FullName = "Алексей Сидоров", Course = 4 }
}, },
ColumnPropertyMappings = new Dictionary<int, string> Columns = new List<(string, float, string, int)>
{ {
{ 0, nameof(Student.Group) }, ("№", 1.0f, nameof(Student.Number), 0),
{ 1, nameof(Student.FullName) }, ("Группа", 4.0f, nameof(Student.Group), 1),
{ 2, nameof(Student.Course) } ("ФИО", 6.0f, nameof(Student.FullName), 2),
} ("Курс", 2.0f, nameof(Student.Course), 3)
}
}; };
try try
@ -202,14 +201,12 @@ namespace Forms
{ {
new ChartData { SeriesName = "Серияd 1", Data = new Dictionary<string, double> { { "Категорияz 1", 5 }, { "Категорияx 2", 10 } } }, new ChartData { SeriesName = "Серияd 1", Data = new Dictionary<string, double> { { "Категорияz 1", 5 }, { "Категорияx 2", 10 } } },
new ChartData { SeriesName = "Серияs 2", Data = new Dictionary<string, double> { { "Категорияa 1", 3 }, { "Категорияs 2", 8 } } }, new ChartData { SeriesName = "Серияs 2", Data = new Dictionary<string, double> { { "Категорияa 1", 3 }, { "Категорияs 2", 8 } } },
new ChartData { SeriesName = "Серияs 2", Data = new Dictionary<string, double> { { "Категорияa 1", 3 }, { "Категорияs 2", 8 } } } new ChartData { SeriesName = "Серияs 3", Data = new Dictionary<string, double> { { "Категорияa 1", 3 }, { "Категорияs 2", 8 } } }
}; };
// Укажите путь, куда хотите сохранить PDF string filePath = "E:\\Гистограмма.pdf";
string filePath = "G:\\Гистограмма.pdf";
// Генерация PDF histogramGenerator.CreateHistogramPdf(filePath, "Название документа", "Заголовок гистограммы", LegendPosition.BottomCenter, chartData);
histogramGenerator.CreateHistogramPdf(filePath, "Название документа", "Заголовок диаграммы", LegendPositions.Bottom, chartData);
MessageBox.Show("PDF успешно сгенерирован!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information); MessageBox.Show("PDF успешно сгенерирован!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
} }