вроде работает

This commit is contained in:
annalyovushkina@yandex.ru 2024-09-22 18:39:37 +04:00
parent 1f8701e03c
commit 381c248106
15 changed files with 692 additions and 2 deletions

View File

@ -7,4 +7,9 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="PDFsharp-MigraDoc" Version="6.1.1" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomComponents.Helpers
{
public class DataForImage
{
public DataForImage(string filepath, string header, string[] imagepaths)
{
this.filepath = filepath;
this.header = header;
this.imagepaths = imagepaths;
}
public string filepath;
public string header;
public string[] imagepaths;
}
}

View File

@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomComponents.Helpers
{
public class DataForPieChart
{
public string FilePath = string.Empty;
public string DocumentTitle = string.Empty;//заголовок документа
public string ChartTitle = string.Empty;//заголовок диаграммы
public DiagramLegendEnum diagLegend;
public string LegendName = string.Empty;
public List<(double, string)> Items;
public DataForPieChart(string filePath, string documentTitle, string charttitle, DiagramLegendEnum diagLegend, string legendName, List<(double, string)> items)
{
FilePath = filePath;
DocumentTitle = documentTitle;
ChartTitle = charttitle;
this.diagLegend = diagLegend;
LegendName = legendName;
Items = items;
}
}
}

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomComponents.Helpers
{
public class DataForTable<T>
{
public string FilePath = string.Empty;
public string DocumentTitle = string.Empty;
public List<int> Heights;
public List<(int, int)> Merges;
public List<(string props, string heads)> Headers;
public List<T> Data;
public DataForTable(string filePath, string documentTitle, List<int> heights, List<(int, int)> merges, List<(string, string)> headers, List<T> data)
{
FilePath = filePath;
DocumentTitle = documentTitle;
Heights = heights;
Merges = merges;
Headers = headers;
Data = data;
}
}
}

View File

@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomComponents.Helpers
{
public enum DiagramLegendEnum
{
Top = 0,
Bottom = 1,
Right = 2,
Left = 3,
}
}

View File

@ -0,0 +1,36 @@
namespace CustomComponents.NonVisualComponents
{
partial class PdfImage
{
/// <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,69 @@
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using CustomComponents.Helpers;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CustomComponents.NonVisualComponents
{
public partial class PdfImage : Component
{
public PdfImage()
{
InitializeComponent();
}
public PdfImage(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool CreatePdfDoc(DataForImage dataForImage)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
CheckFileExsists(dataForImage);
Document _document = new Document();
var style = _document.Styles["Normal"];
style.Font.Name = "Arial";
style.Font.Size = 25;
style = _document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
var section = _document.AddSection();
var paragraph = section.AddParagraph(dataForImage.header);
paragraph.Format.Alignment = ParagraphAlignment.Center;
paragraph.Format.SpaceAfter = "2cm";
foreach (string path in dataForImage.imagepaths)
if (File.Exists(path)) section.AddImage(path);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(dataForImage.filepath);
return true;
}
private void CheckFileExsists(DataForImage dataForImage)
{
if (string.IsNullOrEmpty(dataForImage.filepath) || string.IsNullOrEmpty(dataForImage.header) || dataForImage.imagepaths.Length == 0)
{
throw new ArgumentNullException();
}
if (!File.Exists(dataForImage.filepath))
{
throw new FileNotFoundException(dataForImage.filepath);
}
}
}
}

View File

@ -0,0 +1,36 @@
namespace CustomComponents.NonVisualComponents
{
partial class PdfPieChart
{
/// <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,89 @@
using CustomComponents.Helpers;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using MigraDoc.DocumentObjectModel.Shapes.Charts;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MigraDoc.DocumentObjectModel.Visitors;
namespace CustomComponents.NonVisualComponents
{
public partial class PdfPieChart : Component
{
public PdfPieChart()
{
InitializeComponent();
}
public PdfPieChart(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool CreatePieChart(DataForPieChart dataForPDFPie)
{
// проверки
if (string.IsNullOrEmpty(dataForPDFPie.FilePath) || string.IsNullOrEmpty(dataForPDFPie.DocumentTitle) || string.IsNullOrEmpty(dataForPDFPie.ChartTitle)
|| string.IsNullOrEmpty(dataForPDFPie.LegendName)
|| dataForPDFPie.Items.Count == 0) throw new ArgumentException("Недостаточно данных");
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Document _document = new Document();
var style = _document.Styles["Normal"];
style.Font.Name = "Arial";
var section = _document.AddSection();
var paragraph = section.AddParagraph(dataForPDFPie.DocumentTitle);
paragraph.Format.Font.Size = 25;
paragraph.Format.Alignment = ParagraphAlignment.Center;
paragraph.Format.SpaceAfter = "2cm";
Chart chart = section.AddChart(ChartType.Pie2D);
chart.Width = Unit.FromCentimeter(16);
chart.Height = Unit.FromCentimeter(16);
chart.HeaderArea.AddParagraph(dataForPDFPie.ChartTitle); // заголовок диаграммы
Series series = chart.SeriesCollection.AddSeries();
series.Name = dataForPDFPie.LegendName; // название сериии
XSeries xseries = chart.XValues.AddXSeries();
foreach ((double, string) el in dataForPDFPie.Items) // заполнение серии
{
series.Add(el.Item1);
xseries.Add(el.Item2);
}
switch (dataForPDFPie.diagLegend) // позиция легенды
{
case DiagramLegendEnum.Top:
chart.TopArea.AddLegend();
break;
case DiagramLegendEnum.Bottom:
chart.BottomArea.AddLegend();
break;
case DiagramLegendEnum.Right:
chart.RightArea.AddLegend();
break;
case DiagramLegendEnum.Left:
chart.LeftArea.AddLegend();
break;
}
chart.DataLabel.Type = DataLabelType.Percent;
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(dataForPDFPie.FilePath);
return true;
}
}
}

View File

@ -0,0 +1,36 @@
namespace CustomComponents.NonVisualComponents
{
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,176 @@
using CustomComponents.Helpers;
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.Text;
using System.Threading.Tasks;
namespace CustomComponents.NonVisualComponents
{
public partial class PdfTable : Component
{
public PdfTable()
{
InitializeComponent();
}
public PdfTable(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public bool createTable<T>(DataForTable<T> dataForPDF)
{
//проверки
if (dataForPDF.Merges.Count == 0 || dataForPDF.Heights.Count == 0 || dataForPDF.Headers.Count == 0
|| dataForPDF.Data.Count == 0 || string.IsNullOrEmpty(dataForPDF.FilePath)
|| string.IsNullOrEmpty(dataForPDF.DocumentTitle)) throw new ArgumentException("Недостаточно данных");
int[] cellsArray = new int[dataForPDF.Heights.Count];
foreach (var merge in dataForPDF.Merges)
{
if (merge.Item1 >= merge.Item2) throw new ArgumentException("Неправильно заполнены объединения строк");
for (int i = merge.Item1; i < merge.Item2; i++)
{
cellsArray[i]++;
}
}
foreach (int cell in cellsArray)
{
if (cell > 1) throw new ArgumentException("Объединения заходят друг на друга");
}
foreach ((string, string) el in dataForPDF.Headers)
if (string.IsNullOrEmpty(el.Item2)) throw new ArgumentException("Элементы шапки не могут быть пустыми");
//создание документа
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Document _document = new Document();
var style = _document.Styles["Normal"];
style = _document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Name = "Arial";
style.Font.Size = 25;
style.Font.Bold = true;
style = _document.Styles.AddStyle("Table", "Normal");
style.Font.Name = "Arial";
style.Font.Size = 10;
//добавление заголовка
var section = _document.AddSection();
var paragraph = section.AddParagraph(dataForPDF.DocumentTitle);
paragraph.Format.Alignment = ParagraphAlignment.Center;
paragraph.Format.SpaceAfter = "2cm";
paragraph.Style = "NormalTitle";
//добавление таблицы
Table table = section.AddTable();
table.Style = "Table";
table.Borders.Width = 0.25;
Column column;
for (int i = 0; i < dataForPDF.Data.Count + 2; i++)
{
column = table.AddColumn();
column.Format.Alignment = ParagraphAlignment.Center;
}
// создание шапки и заполнение контентом
int mergeRange = 0; //размерность слияния
int mergeIndex = 0; //стартовый индекс начала слияния
Row row;
for (int i = 0; i < dataForPDF.Headers.Count; i++)
{
//если элемент шапки группируются по строкам
if (dataForPDF.Merges.Select(x => x.Item1).Contains(mergeIndex))
{
mergeRange = dataForPDF.Merges.Find(x => x.Item1 == mergeIndex).Item2 - mergeIndex;
mergeIndex = dataForPDF.Merges.Find(x => x.Item1 == mergeIndex).Item2 + 1;
//стилизация ячейки. в этом блоке кода (до цикла) создаётся объединяющая ячейка
row = table.AddRow();
row.Height = dataForPDF.Heights[i];
row.Format.Alignment = ParagraphAlignment.Center;
row.Format.Font.Bold = true;
row.Cells[0].AddParagraph(dataForPDF.Headers[i].Item2);
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row.Cells[0].MergeDown = mergeRange;
//с этого места создаются дочерние ячейки
for (int k = 0; k < mergeRange; k++)
{
i++;
row.Cells[1].AddParagraph(dataForPDF.Headers[i].Item2);
AddTheContent<T>(dataForPDF.Data, table, dataForPDF.Headers[i].Item1, row.Index, 2);
row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
row = table.AddRow();
row.Height = dataForPDF.Heights[i];
row.Format.Font.Bold = true;
row.Format.Alignment = ParagraphAlignment.Center;
}
i++;
row.Cells[1].AddParagraph(dataForPDF.Headers[i].Item2);
AddTheContent<T>(dataForPDF.Data, table, dataForPDF.Headers[i].Item1, row.Index, 2);
row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
}
else //если элемент шапки не группируется по строкам
{
//стилизация ячейки
row = table.AddRow();
row.Height = dataForPDF.Heights[i];
row.Format.Font.Bold = true;
row.Format.Alignment = ParagraphAlignment.Center;
row.Cells[0].AddParagraph(dataForPDF.Headers[i].Item2);
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
row.Cells[0].MergeRight = 1;
AddTheContent<T>(dataForPDF.Data, table, dataForPDF.Headers[i].Item1, row.Index, 2);
mergeIndex++;
}
}
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = _document;
renderer.RenderDocument();
renderer.PdfDocument.Save(dataForPDF.FilePath);
return true;
}
//метод заполнения таблицы контентом, заполнение происходит построчно.
public void AddTheContent<T>(List<T> items, Table table, string header, int row_index, int cell_index)
{
foreach (Row r in table.Rows)
{
for (int i = 0; i < items.Count; i++)
{
if (r.Index == row_index && row_index == 0) r.Cells[cell_index + i].AddParagraph((i + 1).ToString());
else if (row_index != 0 && r.Index == row_index)
{
T item = items[i];
var type = typeof(T);
var fields = type.GetFields();
var field = fields.FirstOrDefault(x => x.Name.Equals(header));
r.Cells[cell_index + i].AddParagraph(field.GetValue(item).ToString());
r.Cells[cell_index + i].VerticalAlignment = VerticalAlignment.Center;
}
}
}
}
}
}

View File

@ -28,6 +28,7 @@
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
customComboBox1 = new KOP_Labs.CustomComboBox();
customListBox1 = new KOP_Labs.CustomListBox();
customTree1 = new KOP_Labs.CustomTree();
@ -37,6 +38,13 @@
labelItem = new Label();
buttonCheck = new Button();
checkBoxValid = new CheckBox();
pdfImage1 = new CustomComponents.NonVisualComponents.PdfImage(components);
buttonPdfImage = new Button();
openFileDialog1 = new OpenFileDialog();
buttonPdfTable = new Button();
pdfTable1 = new CustomComponents.NonVisualComponents.PdfTable(components);
buttonPdfChart = new Button();
pdfPieChart1 = new CustomComponents.NonVisualComponents.PdfPieChart(components);
SuspendLayout();
//
// customComboBox1
@ -47,7 +55,6 @@
customComboBox1.Name = "customComboBox1";
customComboBox1.Size = new Size(301, 125);
customComboBox1.TabIndex = 0;
customComboBox1.TextBoxValue = "";
//
// customListBox1
//
@ -124,11 +131,49 @@
checkBoxValid.Text = "Проверка";
checkBoxValid.UseVisualStyleBackColor = true;
//
// buttonPdfImage
//
buttonPdfImage.Location = new Point(12, 522);
buttonPdfImage.Name = "buttonPdfImage";
buttonPdfImage.Size = new Size(208, 29);
buttonPdfImage.TabIndex = 10;
buttonPdfImage.Text = "Создать pdf с картинкой";
buttonPdfImage.UseVisualStyleBackColor = true;
buttonPdfImage.Click += buttonPdfImage_Click;
//
// openFileDialog1
//
openFileDialog1.FileName = "openFileDialog1";
openFileDialog1.Multiselect = true;
//
// buttonPdfTable
//
buttonPdfTable.Location = new Point(304, 522);
buttonPdfTable.Name = "buttonPdfTable";
buttonPdfTable.Size = new Size(213, 29);
buttonPdfTable.TabIndex = 11;
buttonPdfTable.Text = "Создать pdf с таблицей";
buttonPdfTable.UseVisualStyleBackColor = true;
buttonPdfTable.Click += buttonPdfTable_Click;
//
// buttonPdfChart
//
buttonPdfChart.Location = new Point(602, 522);
buttonPdfChart.Name = "buttonPdfChart";
buttonPdfChart.Size = new Size(224, 29);
buttonPdfChart.TabIndex = 12;
buttonPdfChart.Text = "Создать pdf с диаграммой";
buttonPdfChart.UseVisualStyleBackColor = true;
buttonPdfChart.Click += buttonPdfChart_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1042, 573);
Controls.Add(buttonPdfChart);
Controls.Add(buttonPdfTable);
Controls.Add(buttonPdfImage);
Controls.Add(checkBoxValid);
Controls.Add(buttonCheck);
Controls.Add(labelItem);
@ -155,5 +200,12 @@
private Label labelItem;
private Button buttonCheck;
private CheckBox checkBoxValid;
private CustomComponents.NonVisualComponents.PdfImage pdfImage1;
private Button buttonPdfImage;
private OpenFileDialog openFileDialog1;
private Button buttonPdfTable;
private CustomComponents.NonVisualComponents.PdfTable pdfTable1;
private Button buttonPdfChart;
private CustomComponents.NonVisualComponents.PdfPieChart pdfPieChart1;
}
}

View File

@ -1,3 +1,4 @@
using CustomComponents.Helpers;
using WinFormForTest.TestClasses;
namespace WinFormForTest
@ -72,5 +73,67 @@ namespace WinFormForTest
labelItem.Text = customListBox1.SelectedElement;
}
private void buttonPdfImage_Click(object sender, EventArgs e)
{
var res = openFileDialog1.ShowDialog(this);
if (res != DialogResult.OK) return;
var files = openFileDialog1.FileNames;
openFileDialog1.Dispose();
string path = "C:\\Users\\annal\\Desktop\\test_cop_lab2\\testImage.pdf";
MessageBox.Show(path);
if (pdfImage1.CreatePdfDoc(new DataForImage(path, "Êàðòèíêè", files))) MessageBox.Show("Success!");
else MessageBox.Show("Error");
}
private void buttonPdfTable_Click(object sender, EventArgs e)
{
List<Film> films = new List<Film>()
{
new Film("Ìàñêà", "êîìåäèÿ, êðèìèíàë, ôýíòåçè", "1÷. 36ìèí.", "12+"),
new Film("Çâ¸çäíàÿ ïûëü", "ìåëîäðàìà, ïðèêëþ÷åíèÿ, ôýíòåçè", "2÷. 7ìèí.", "18+"),
new Film("Àâàòàð", "ïðèêëþ÷åíèÿ, ôàíòàñòèêà, áîåâèê, äðàìà", "2÷. 58ìèí.", "18+"),
new Film("Êîíñòàíòèí", "ôýíòåçè, óæàñû, áîåâèê, äåòåêòèâ", "2÷. 1ìèí.", "18+")
};
List<(int, int)> merges = new List<(int, int)>();
merges.Add((1, 2));
List<int> heights = new List<int> { 10, 80, 30, 50, 25, 25 };
string path = "C:\\Users\\annal\\Desktop\\test_cop_lab2\\testTable.pdf";
List<(string, string)> headers = new List<(string, string)>
{
("id", "Id"),
("", "Ôèëüì"),
("Name", "Íàçâàíèå"),
("Ganre", "Æàíð"),
("Duration", "Ïðîäîëæèòåëüíîñòü"),
("AgeRange", "Âîçðàñòíîå îãðàíè÷åíèå")
};
if (pdfTable1.createTable(new DataForTable<Film>(path, "Òàáëèöà ôèëüìîâ", heights, merges, headers, films)))
{
MessageBox.Show("Success");
}
}
private void buttonPdfChart_Click(object sender, EventArgs e)
{
string path = "C:\\Users\\annal\\Desktop\\test_cop_lab2\\testPieChart.pdf";
List<(double, string)> elements = new List<(double, string)>
{
(20, "Êîëÿ"),
(37, "Äàøà"),
(10, "Åãîð"),
(15, "Òàíÿ"),
(18, "Âàëåðà")
};
if (pdfPieChart1.CreatePieChart(new DataForPieChart(path, "Êðóãîâàÿ äèàãðàììà", "Óñïåõ ïðîñìîòðà 100 ôèëüìîâ", DiagramLegendEnum.Bottom, "Ïðîñìîòðåíî", elements)))
{
MessageBox.Show("Success");
}
}
}
}

View File

@ -117,4 +117,16 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="pdfImage1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>146, 17</value>
</metadata>
<metadata name="pdfTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>316, 17</value>
</metadata>
<metadata name="pdfPieChart1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>438, 17</value>
</metadata>
</root>

View File

@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WinFormForTest.TestClasses
{
public class Film
{
public string Name;
public string Ganre;
public string Duration;
public string AgeRange;
public Film(string name, string ganre, string duration, string ageRange)
{
Name = name;
Ganre = ganre;
Duration = duration;
AgeRange = ageRange;
}
}
}