3 of 3 comps done

This commit is contained in:
DavidMakarov 2024-10-16 01:47:44 +04:00
parent 13ba5c0649
commit d803f6226f
14 changed files with 490 additions and 5 deletions

View File

@ -8,7 +8,6 @@
</PropertyGroup>
<ItemGroup>
<Folder Include="SaveToPdfHelpers\" />
<PackageReference Include="PdfSharp.MigraDoc.Standard" Version="1.51.15" />
</ItemGroup>

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Components.Nonvisual
{
public enum LegendAlignment
{
Top,
Bottom,
Left,
Right
}
}

View File

@ -0,0 +1,36 @@
namespace Components.Nonvisual
{
partial class UserControlConfigurableTableDocument
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,41 @@
using MigraDoc.DocumentObjectModel.Tables;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Components.Nonvisual
{
public partial class UserControlConfigurableTableDocument : Component
{
public UserControlConfigurableTableDocument()
{
InitializeComponent();
}
public UserControlConfigurableTableDocument(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void SaveToDocument<T>(string filePath, string title,
List<(double width, string header, string propName)> columns,
double headerRowHeight, double rowHeight, List<T> data)
{
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException("Empty string instead of path to file");
if (string.IsNullOrEmpty(title)) throw new ArgumentNullException("Title string is empty");
if (data.Count == 0) throw new ArgumentNullException("Data list is empty");
if (columns.Count == 0) throw new ArgumentNullException("Column info list is empty");
if (rowHeight == 0D || headerRowHeight == 0D) throw new ArgumentNullException("Row height is empty");
SaveToPdf saver = new SaveToPdf();
saver.CreateConfigurableTableDocument(filePath, title, columns, headerRowHeight, rowHeight, data);
}
}
}

View File

@ -0,0 +1,36 @@
namespace Components.Nonvisual
{
partial class UserControlHist
{
/// <summary>
/// Обязательная переменная конструктора.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Освободить все используемые ресурсы.
/// </summary>
/// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Код, автоматически созданный конструктором компонентов
/// <summary>
/// Требуемый метод для поддержки конструктора — не изменяйте
/// содержимое этого метода с помощью редактора кода.
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
}
#endregion
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace Components.Nonvisual
{
public partial class UserControlHist : Component
{
public UserControlHist()
{
InitializeComponent();
}
public UserControlHist(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateHist(string filePath, string title, string histTitle,
LegendAlignment alignment, Dictionary<string, int[]> data)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentException("Filename cannot be empty");
if (string.IsNullOrEmpty(title))
throw new ArgumentException("Title cannot be empty");
if (string.IsNullOrEmpty(histTitle))
throw new ArgumentException("Hist title cannot be empty");
if (data.Count == 0)
throw new ArgumentException("Data cannot be empty");
SaveToPdf saver = new SaveToPdf();
saver.CreateHist(filePath, title, histTitle, alignment, data);
}
}
}

View File

@ -30,7 +30,7 @@ namespace Components
SaveToPdf saver = new SaveToPdf();
saver.CreateDoc(filePath, header, tables);
saver.CreateTableDocumentWithContext(filePath, header, tables);
}
}
}

View File

@ -3,6 +3,10 @@ using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using Components.SaveToPdfHelpers;
using System.Text;
using System.Security.Cryptography;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using Components.Nonvisual;
using System.IO;
namespace Components
{
@ -11,7 +15,7 @@ namespace Components
private Document? _document;
private Section? _section;
private Table? _table;
public void CreateDoc(string title, string path, List<string[][]> tables)
public void CreateTableDocumentWithContext(string title, string path, List<string[][]> tables)
{
_document = new Document();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
@ -51,6 +55,102 @@ namespace Components
renderer.RenderDocument();
renderer.PdfDocument.Save(path);
}
public void CreateConfigurableTableDocument<T>(string path, string title,
List<(double width, string header, string propName)> columns, double headerRowHeight,
double rowHeight, List<T> data)
{
_document = new Document();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
DefineStyles(_document);
_section = _document.AddSection();
CreateParagraph(new PdfParagraph
{
Text = title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateTable(columns.Select(c => c.width).ToList());
CreateRow(new PdfRowParameters
{
Texts = columns.Select(c => c.header).ToList(),
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center,
RowHeight = headerRowHeight,
});
foreach (var obj in data)
{
List<string> cells = new List<string>();
for (int i = 0; i < columns.Count; i++)
{
var propName = columns[i].propName;
var prop = typeof(T).GetProperty(propName);
if (prop is null)
{
throw new ArgumentException($"Failed to find property {prop} in provided objects class");
}
var propVal = prop.GetValue(obj)?.ToString();
if (propVal is not null)
{
cells.Add(propVal);
}
}
CreateRow(new PdfRowParameters
{
Texts = cells,
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left,
FirstCellStyle = "NormalTitle",
FirstCellParagraphAlignment = PdfParagraphAlignmentType.Center,
RowHeight = rowHeight,
});
}
CreateParagraph(new PdfParagraph());
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(path);
}
public void CreateHist(string filePath, string title, string histTitle,
LegendAlignment alignment, Dictionary<string, int[]> data)
{
_document = new Document();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
DefineStyles(_document);
_section = _document.AddSection();
CreateParagraph(new PdfParagraph
{
Text = title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
CreateChart(new PdfChartParameters
{
Data = data,
Title = histTitle,
LegendAlignment = alignment,
});
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(filePath);
}
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type)
{
return type switch
@ -92,6 +192,19 @@ namespace Components
_table.AddColumn(elem);
}
}
protected void CreateTable(List<double> columnWidths)
{
if (_document == null)
{
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columnWidths)
{
_table.AddColumn(Unit.FromCentimeter(elem));
}
}
protected void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
@ -102,18 +215,70 @@ namespace Components
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[i]);
if (!string.IsNullOrEmpty(rowParameters.Style))
if (i == 0 && !string.IsNullOrEmpty(rowParameters.FirstCellStyle))
{
row.Cells[i].Style = rowParameters.FirstCellStyle;
}
else if (!string.IsNullOrEmpty(rowParameters.Style))
{
row.Cells[i].Style = rowParameters.Style;
}
if (i == 0 && rowParameters.FirstCellParagraphAlignment != null)
{
row.Cells[i].Format.Alignment = GetParagraphAlignment((PdfParagraphAlignmentType)rowParameters.FirstCellParagraphAlignment);
}
else
{
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
}
if (rowParameters.RowHeight is not null)
{
row.Height = Unit.FromCentimeter((double)rowParameters.RowHeight);
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected void CreateChart(PdfChartParameters chartParams)
{
if (_section == null)
return;
Chart chart = new Chart(ChartType.Bar2D);
chart.Width = "15cm";
chart.Height = "8cm";
foreach (var dataSeries in chartParams.Data)
{
Series series = chart.SeriesCollection.AddSeries();
series.Name = dataSeries.Key;
series.Add(dataSeries.Value.Select(x => (double)x).ToArray());
}
chart.TopArea.AddParagraph(chartParams.Title);
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.HasMajorGridlines = true;
_ = chartParams.LegendAlignment switch
{
LegendAlignment.Top => chart.TopArea.AddLegend(),
LegendAlignment.Right => chart.RightArea.AddLegend(),
LegendAlignment.Bottom => chart.BottomArea.AddLegend(),
LegendAlignment.Left => chart.LeftArea.AddLegend(),
_ => chart.BottomArea.AddLegend(),
};
chart.PlotArea.LineFormat.Width = 1;
chart.PlotArea.LineFormat.Visible = true;
_section.Add(chart);
}
}
}

View File

@ -0,0 +1,18 @@
using Components.Nonvisual;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Components.SaveToPdfHelpers
{
internal class PdfChartParameters
{
public Dictionary<string, int[]> Data = new();
public string Title = string.Empty;
public LegendAlignment LegendAlignment = LegendAlignment.Bottom;
}
}

View File

@ -5,6 +5,10 @@ namespace Components.SaveToPdfHelpers
{
public List<string> Texts { get; set; } = new();
public string Style { get; set; } = string.Empty;
public double? RowHeight { get; set; }
public PdfParagraphAlignmentType ParagraphAlignment { get; set; }
public string FirstCellStyle { get; set; } = string.Empty;
public PdfParagraphAlignmentType? FirstCellParagraphAlignment { get; set; }
}
}

View File

@ -31,6 +31,10 @@
components = new System.ComponentModel.Container();
userControlTableDocument1 = new Components.UserControlTableDocument(components);
button1 = new Button();
button2 = new Button();
userControlConfigurableTableDocument1 = new Components.Nonvisual.UserControlConfigurableTableDocument(components);
button3 = new Button();
userControlHist1 = new Components.Nonvisual.UserControlHist(components);
SuspendLayout();
//
// button1
@ -43,11 +47,33 @@
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// button2
//
button2.Location = new Point(218, 12);
button2.Name = "button2";
button2.Size = new Size(188, 65);
button2.TabIndex = 1;
button2.Text = "Сохранить второй компонент";
button2.UseVisualStyleBackColor = true;
button2.Click += button2_Click;
//
// button3
//
button3.Location = new Point(433, 12);
button3.Name = "button3";
button3.Size = new Size(188, 65);
button3.TabIndex = 2;
button3.Text = "Сохранить третий компонент";
button3.UseVisualStyleBackColor = true;
button3.Click += button3_Click;
//
// FormMain
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(button3);
Controls.Add(button2);
Controls.Add(button1);
Name = "FormMain";
Text = "Testing form";
@ -58,5 +84,9 @@
private Components.UserControlTableDocument userControlTableDocument1;
private Button button1;
private Button button2;
private Components.Nonvisual.UserControlConfigurableTableDocument userControlConfigurableTableDocument1;
private Button button3;
private Components.Nonvisual.UserControlHist userControlHist1;
}
}

View File

@ -1,3 +1,5 @@
using Components.Nonvisual;
namespace TestingForm
{
public partial class FormMain : Form
@ -44,5 +46,71 @@ namespace TestingForm
}
MessageBox.Show("Óñïåøíî");
}
private void button2_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "pdf|*.pdf",
};
if (dialog.ShowDialog() == DialogResult.OK)
{
List<TestUser> users = new List<TestUser>
{
new TestUser(1, "user 1", 20, 50000),
new TestUser(2, "user 2", 19, 30000),
new TestUser(3, "user 3", 26, 70000)
};
try
{
userControlConfigurableTableDocument1.SaveToDocument(
dialog.FileName,
"Çàãîëîâîê äîêóìåíòà",
new List<(double width, string header, string propName)>
{
(2.0, "ID", "Id"),
(6.0, "Èìÿ", "Name"),
(2.0, "Âîçðàñò", "Age"),
(6.0, "Çàðïëàòà", "Salary"),
},
7.0,
2.0,
users
);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Óñïåøíî");
}
private void button3_Click(object sender, EventArgs e)
{
using var dialog = new SaveFileDialog
{
Filter = "pdf|*.pdf",
};
if (dialog.ShowDialog() == DialogResult.OK)
{
Dictionary<string, int[]> data = new Dictionary<string, int[]>
{
{ "test 1", new int[] {1, 2, 3, 6, 7, 9} },
{ "test 2", new int[] {6, 8, 11, 16, 4, 2} },
};
try
{
userControlHist1.CreateHist(dialog.FileName, "Çàãîëîâîê", "Test", LegendAlignment.Bottom, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Îøèáêà", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
MessageBox.Show("Óñïåøíî");
}
}
}

View File

@ -120,4 +120,10 @@
<metadata name="userControlTableDocument1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="userControlConfigurableTableDocument1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>222, 17</value>
</metadata>
<metadata name="userControlHist1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>496, 17</value>
</metadata>
</root>

24
TestingForm/TestUser.cs Normal file
View File

@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestingForm
{
public class TestUser
{
public int Id { get; private set; }
public string Name { get; private set; }
public int Age { get; private set; }
public int Salary { get; private set; }
public TestUser(int id, string name, int age, int salary)
{
Id = id;
Name = name;
Age = age;
Salary = salary;
}
}
}