This commit is contained in:
frog24 2024-10-16 13:59:02 +03:00
parent 77764ab6fa
commit afd75a94eb
27 changed files with 574 additions and 20 deletions

View File

@ -7,4 +7,8 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PDFsharp-MigraDoc-GDI" Version="6.1.1" />
</ItemGroup>
</Project>

View File

@ -4,7 +4,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Components.Exceptions
namespace BarsukovComponents.Exceptions
{
public class CustomException: Exception
{

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarsukovComponents.NotVisualComponents.Configs
{
public class ColumnInfo
{
public string PropertyName;
public string Header;
public int Width;
public ColumnInfo(string propertyName, string header, int width)
{
PropertyName = propertyName;
Header = header;
Width = width;
}
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarsukovComponents.NotVisualComponents.Configs
{
public enum LengendAlign
{
top, bottom, left, right
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarsukovComponents.NotVisualComponents.Configs
{
public class MergeCells
{
public string Header;
public int[] Indexes;
public MergeCells(string header, int[] indexes)
{
Header=header;
Indexes=indexes;
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarsukovComponents.NotVisualComponents.Configs
{
public class TextPdfConf
{
public string Filename { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public List<string> Rows { get; set; } = new();
}
}

View File

@ -0,0 +1,36 @@
namespace BarsukovComponents.NotVisualComponents
{
partial class PdfDiagram
{
/// <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,87 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BarsukovComponents.NotVisualComponents.Configs;
using PdfSharp.Charting;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
namespace BarsukovComponents.NotVisualComponents
{
public partial class PdfDiagram : Component
{
public PdfDiagram()
{
InitializeComponent();
}
public PdfDiagram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateDiagram(string filename, string title, string diagramName, Dictionary<string, List<double>> data, LengendAlign legendAlign = LengendAlign.bottom)
{
if (string.IsNullOrEmpty(filename))
{
throw new ArgumentNullException("Enter filemale");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException("Enter title");
}
if (data.Count == 0)
{
throw new ArgumentNullException("Enter data");
}
Chart chart = new Chart(ChartType.Line);
chart.Legend.Docking = (DockingType)legendAlign;
chart.Legend.LineFormat.Visible = true;
foreach (var item in data)
{
Series series = chart.SeriesCollection.AddSeries();
series.Name = item.Key;
double[] values = new double[item.Value.Count];
for (int i = 0; i < item.Value.Count; i++)
{
values.SetValue(Convert.ToDouble(item.Value[i]), i);
}
series.Add(values);
}
chart.XAxis.MajorTickMark = TickMarkType.Outside;
chart.YAxis.MajorTickMark = TickMarkType.Cross;
chart.PlotArea.LineFormat.Color = XColors.Black;
chart.PlotArea.LineFormat.Visible = true;
chart.PlotArea.FillFormat.Color = XColors.White;
chart.Legend.LineFormat.Visible = true;
ChartFrame chartFrame = new ChartFrame();
chartFrame.Location = new XPoint(50, 70);
chartFrame.Size = new XSize(500, 400);
chartFrame.Add(chart);
PdfDocument document = new PdfDocument(filename);
PdfPage page = document.AddPage();
page.Size = PdfSharp.PageSize.A4;
XGraphics gfx = XGraphics.FromPdfPage(page);
gfx.DrawString(title, new XFont("Times new Roman", 20, XFontStyleEx.Bold), XBrushes.Black, new XRect(20, 20, page.Width, page.Height), XStringFormats.TopCenter);
gfx.DrawString(diagramName, new XFont("Times new Roman", 14), XBrushes.Black, new XRect(20, 40, page.Width, page.Height), XStringFormats.TopCenter);
chartFrame.DrawChart(gfx);
document.Close();
}
}
}

View File

@ -0,0 +1,36 @@
namespace BarsukovComponents.NotVisualComponents
{
partial class PdfHugeText
{
/// <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,56 @@
using BarsukovComponents.NotVisualComponents.Configs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using MigraDoc;
using MigraDoc.DocumentObjectModel;
using PdfSharp.Pdf;
using MigraDoc.Rendering;
using BarsukovComponents.Exceptions;
namespace BarsukovComponents.NotVisualComponents
{
public partial class PdfHugeText : Component
{
public PdfHugeText()
{
InitializeComponent();
}
public PdfHugeText(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreatePdf(TextPdfConf conf)
{
if (string.IsNullOrEmpty(conf.Filename) || string.IsNullOrEmpty(conf.Title) || conf.Rows.Count == 0)
{
throw new CustomException("Путь до файла, заголовок или текст пусты");
}
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraphTitle = section.AddParagraph();
paragraphTitle.AddText(conf.Title);
paragraphTitle.Format.Font.Bold = true;
paragraphTitle.Format.Font.Size = 20;
paragraphTitle.Format.SpaceAfter = "0.3cm";
Paragraph paragraph = section.AddParagraph();
paragraph.Format.Font.Size = 14;
foreach (var row in conf.Rows)
{
paragraph.AddText(row + '\n');
}
var renderer = new PdfDocumentRenderer(true);
renderer.Document = document;
renderer.RenderDocument();
renderer.PdfDocument.Save(conf.Filename);
}
}
}

View File

@ -0,0 +1,36 @@
namespace BarsukovComponents.NotVisualComponents
{
partial class PdfTable
{
/// <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,151 @@
using BarsukovComponents.NotVisualComponents.Configs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using MigraDoc;
using MigraDoc.DocumentObjectModel;
using PdfSharp.Pdf;
using MigraDoc.Rendering;
using BarsukovComponents.Exceptions;
namespace BarsukovComponents.NotVisualComponents
{
public partial class PdfTable : Component
{
public PdfTable()
{
InitializeComponent();
}
public PdfTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateTable<T>(string docPath, string title, List<MergeCells>? mergeCells, List<ColumnInfo> colInfo, List<T> data) where T : class, new()
{
if (string.IsNullOrEmpty(docPath))
{
throw new ArgumentNullException("Введите путь до файла!");
}
if (string.IsNullOrEmpty(title))
{
throw new ArgumentNullException("Введите заголовок");
}
if (colInfo == null)
{
throw new ArgumentNullException("Введите все заголовки");
}
if (data == null)
{
throw new ArgumentNullException("Нету информации для вывода");
}
Document _document = new Document();
var style = _document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
Section _section = _document.AddSection();
//Заголовок
var paragraph = _section.AddParagraph(title);
paragraph.Format.SpaceAfter = "0.3cm";
paragraph.Format.Font.Size = "16";
paragraph.Format.Font.Bold = true;
paragraph.Format.Alignment = ParagraphAlignment.Center;
//Создание таблицы
var table = _section.AddTable();
table.Borders.Visible = true;
//Создание колонок
for (int i = 0; i < colInfo.Count; i++)
{
table.AddColumn(colInfo[i].Width);
}
//Создание строк
if (mergeCells != null)
{
table.AddRow();
}
var row = table.AddRow();
for (int i = 0; i < colInfo.Count; i++)
{
row[i].AddParagraph(colInfo[i].Header);
}
List<int> MergeColls = new List<int>();
//Объединение ячеек в строке
if (mergeCells != null)
{
foreach (var cell in mergeCells)
{
MergeColls.AddRange(cell.Indexes[0..]);
table.Rows[0].Cells[cell.Indexes[0]].MergeRight = cell.Indexes[1..].Length;
table.Rows[0].Cells[cell.Indexes[0]].AddParagraph(cell.Header);
}
}
int cellsCount = table.Rows[1].Cells.Count;
//Объединение ячеек в столбце
if (MergeColls.Count != 0)
{
for (int i = 0; i < cellsCount; i++)
{
var cell = table.Rows[0].Cells[i];
if (!MergeColls.Contains(i))
{
cell.MergeDown = 1;
cell.AddParagraph(colInfo[i].Header);
}
}
}
//Вывод данных
int rowData = 2;
foreach (var item in data)
{
var properties = item.GetType().GetProperties();
if (properties.Count() != cellsCount)
{
throw new Exception("Кол-во полей объекта не совпадает с кол-вом колонок");
}
for (int i = 0; i < properties.Count(); i++)
{
var property = properties[i];
var propValue = property.GetValue(item);
if (propValue == null)
{
throw new Exception("Пустое поле");
}
if (property.Name == colInfo[i].PropertyName)
{
if (table.Rows.Count <= rowData)
{
table.AddRow();
}
table.Rows[rowData].Cells[i].AddParagraph(propValue.ToString());
continue;
}
}
rowData++;
}
var renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(docPath);
}
}
}

View File

@ -1,4 +1,4 @@
namespace Components
namespace BarsukovComponents.VisualComponents
{
partial class CustomComboBox
{

View File

@ -8,7 +8,7 @@ using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Components
namespace BarsukovComponents.VisualComponents
{
public partial class CustomComboBox : UserControl
{

View File

@ -1,4 +1,4 @@
namespace Components
namespace BarsukovComponents.VisualComponents
{
partial class CustomListBox
{

View File

@ -10,7 +10,7 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Components
namespace BarsukovComponents.VisualComponents
{
public partial class CustomListBox : UserControl
{

View File

@ -1,4 +1,4 @@
namespace Components
namespace BarsukovComponents.VisualComponents
{
partial class CustomTextBox
{

View File

@ -1,4 +1,4 @@
using Components.Exceptions;
using BarsukovComponents.Exceptions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@ -10,7 +10,7 @@ using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Components
namespace BarsukovComponents.VisualComponents
{
public partial class CustomTextBox : UserControl
{

View File

@ -3,9 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35222.181
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Components", "..\Components\Components.csproj", "{52A015B2-0077-47D3-9BC8-F378C3BCF965}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BarsukovComponents", "..\Components\BarsukovComponents.csproj", "{52A015B2-0077-47D3-9BC8-F378C3BCF965}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestApp", "TestApp\TestApp.csproj", "{BF4A0F84-CD73-443C-A480-B54A9A0B7867}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestApp", "TestApp\TestApp.csproj", "{BF4A0F84-CD73-443C-A480-B54A9A0B7867}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@ -10,5 +10,11 @@ namespace TestApp
{
public string Mood { get; set; }
public DateTime Date { get; set; }
public Day() { }
public Day(string mood, DateTime date)
{
Mood = mood;
Date = date;
}
}
}

View File

@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApp
{
public class Example
{
public string First { get; set; } = string.Empty;
public string Second { get; set; } = string.Empty;
public string Third { get; set; } = string.Empty;
public string Fourth { get; set; } = string.Empty;
public string Fifth { get; set; } = string.Empty;
public Example() { }
public Example(string first, string second, string third, string fourth, string fifth)
{
First=first;
Second=second;
Third=third;
Fourth=fourth;
Fifth=fifth;
}
}
}

View File

@ -1,4 +1,6 @@
namespace TestApp
using BarsukovComponents.NotVisualComponents.Configs;
namespace TestApp
{
partial class Form1
{
@ -28,12 +30,12 @@
/// </summary>
private void InitializeComponent()
{
customComboBox = new Components.CustomComboBox();
customComboBox = new BarsukovComponents.VisualComponents.CustomComboBox();
buttonAdd = new Button();
buttonClear = new Button();
buttonGet = new Button();
customTextBox = new Components.CustomTextBox();
customListBox = new Components.CustomListBox();
customTextBox = new BarsukovComponents.VisualComponents.CustomTextBox();
customListBox = new BarsukovComponents.VisualComponents.CustomListBox();
buttonDay = new Button();
buttonAddDay = new Button();
textBoxMood = new TextBox();
@ -152,18 +154,19 @@
Controls.Add(customComboBox);
Name = "Form1";
Text = "Form1";
Load += MyForm_Load;
ResumeLayout(false);
PerformLayout();
}
#endregion
private Components.CustomComboBox customComboBox;
private BarsukovComponents.VisualComponents.CustomComboBox customComboBox;
private Button buttonAdd;
private Button buttonClear;
private Button buttonGet;
private Components.CustomTextBox customTextBox;
private Components.CustomListBox customListBox;
private BarsukovComponents.VisualComponents.CustomTextBox customTextBox;
private BarsukovComponents.VisualComponents.CustomListBox customListBox;
private Button buttonDay;
private Button buttonAddDay;
private TextBox textBoxMood;

View File

@ -1,5 +1,7 @@
using Components;
using BarsukovComponents;
using BarsukovComponents.NotVisualComponents;
using BarsukovComponents.NotVisualComponents.Configs;
using MigraDoc.DocumentObjectModel;
namespace TestApp
{
public partial class Form1 : Form
@ -97,5 +99,46 @@ namespace TestApp
customListBox.FillProperty(day, index, "Mood");
customListBox.FillProperty(day, index, "Date");
}
private void MyForm_Load(object sender, EventArgs e)
{
TextPdfConf conf = new TextPdfConf();
conf.Filename = "C:/Users/pasha/Desktop/MyDocument.pdf";
conf.Title = "My Document";
conf.Rows = new List<string> { "This is the first row. it's gonna be very long row that should actually take two rows or even more", "This is the second row.", "This is the third row." };
PdfHugeText pdfHugeText = new PdfHugeText();
pdfHugeText.CreatePdf(conf);
// -------------------
List<ColumnInfo> colInfos = new List<ColumnInfo>()
{
new ColumnInfo("First","First Prop",50),
new ColumnInfo("Second","Second Prop",100),
new ColumnInfo("Third","Third Prop",100),
new ColumnInfo("Fourth","Fourth Prop",200),
new ColumnInfo("Fifth","Fifth Prop",50),
};
List<MergeCells> mergeCells = new List<MergeCells>()
{
new MergeCells("Merged columns", new int[] {3,4})
};
List<Example> workers = new List<Example>()
{
new Example("1 ïåðâûé", "1 ýòî âòîðîé)))", "1 òðåòèé", "1 ÷åòûðêà", "1 ïÿòêà"),
new Example("2 ïåðâàê", "2 ýòî âòîðîé âòîðîé)))", "2 òðåòüÿê", "2 õîðîøî", "5 ïÿòêà"),
};
PdfTable pdfTable = new PdfTable();
pdfTable.CreateTable("C:/Users/pasha/Desktop/MyTable.pdf", "TITLE", mergeCells, colInfos, workers);
// -------------------
Dictionary<string, List<double>> data = new();
data.Add("first", new List<double> {0.5, 3, 5, 9 });
data.Add("second", new List<double> {1, 2, 3, 7 });
PdfDiagram pdfDiagram = new PdfDiagram();
pdfDiagram.CreateDiagram("C:/Users/pasha/Desktop/MyDiagram.pdf", "title", "öèôåðêè öèôåðêè", data, LengendAlign.right);
}
}
}

View File

@ -9,7 +9,7 @@
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\Components\Components.csproj" />
<ProjectReference Include="..\..\Components\BarsukovComponents.csproj" />
</ItemGroup>
</Project>