2-й компонент для 2 лабы готов
This commit is contained in:
parent
2068af18d0
commit
233146ea2c
26
TestView/BookInfo.cs
Normal file
26
TestView/BookInfo.cs
Normal file
@ -0,0 +1,26 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TestView
|
||||
{
|
||||
public class BookInfo
|
||||
{
|
||||
public string Redaction;
|
||||
public string AuthorName;
|
||||
public string AuthorSurname;
|
||||
public string AuthorLife;
|
||||
public string Title;
|
||||
|
||||
public BookInfo(string Redaction, string AuthorName, string AuthorSurname, string AuthorLife, string Title)
|
||||
{
|
||||
this.Redaction = Redaction;
|
||||
this.AuthorName = AuthorName;
|
||||
this.AuthorSurname = AuthorSurname;
|
||||
this.AuthorLife = AuthorLife;
|
||||
this.Title = Title;
|
||||
}
|
||||
}
|
||||
}
|
17
TestView/Form1.Designer.cs
generated
17
TestView/Form1.Designer.cs
generated
@ -46,6 +46,8 @@
|
||||
buttonPdfImages = new Button();
|
||||
pdfImages1 = new ViewComponents.NotVisualComponents.PdfImages(components);
|
||||
openFileDialog1 = new OpenFileDialog();
|
||||
pdfTable1 = new ViewComponents.NotVisualComponents.PdfTable(components);
|
||||
buttonTestPdfTable = new Button();
|
||||
SuspendLayout();
|
||||
//
|
||||
// buttonAdd
|
||||
@ -188,7 +190,7 @@
|
||||
//
|
||||
// buttonPdfImages
|
||||
//
|
||||
buttonPdfImages.Location = new Point(60, 363);
|
||||
buttonPdfImages.Location = new Point(36, 393);
|
||||
buttonPdfImages.Name = "buttonPdfImages";
|
||||
buttonPdfImages.Size = new Size(197, 29);
|
||||
buttonPdfImages.TabIndex = 15;
|
||||
@ -201,11 +203,22 @@
|
||||
openFileDialog1.FileName = "openFileDialog1";
|
||||
openFileDialog1.Multiselect = true;
|
||||
//
|
||||
// buttonTestPdfTable
|
||||
//
|
||||
buttonTestPdfTable.Location = new Point(409, 393);
|
||||
buttonTestPdfTable.Name = "buttonTestPdfTable";
|
||||
buttonTestPdfTable.Size = new Size(94, 29);
|
||||
buttonTestPdfTable.TabIndex = 16;
|
||||
buttonTestPdfTable.Text = "button1";
|
||||
buttonTestPdfTable.UseVisualStyleBackColor = true;
|
||||
buttonTestPdfTable.Click += buttonTestPdfTable_Click;
|
||||
//
|
||||
// Form1
|
||||
//
|
||||
AutoScaleDimensions = new SizeF(8F, 20F);
|
||||
AutoScaleMode = AutoScaleMode.Font;
|
||||
ClientSize = new Size(899, 600);
|
||||
Controls.Add(buttonTestPdfTable);
|
||||
Controls.Add(buttonPdfImages);
|
||||
Controls.Add(myTreeView);
|
||||
Controls.Add(buttonSetIndex);
|
||||
@ -246,5 +259,7 @@
|
||||
private Button buttonPdfImages;
|
||||
private ViewComponents.NotVisualComponents.PdfImages pdfImages1;
|
||||
private OpenFileDialog openFileDialog1;
|
||||
private ViewComponents.NotVisualComponents.PdfTable pdfTable1;
|
||||
private Button buttonTestPdfTable;
|
||||
}
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Forms;
|
||||
using ViewComponents.Exeption;
|
||||
using ViewComponents.NotVisualComponents;
|
||||
@ -122,5 +124,29 @@ namespace TestView
|
||||
if (pdfImages1.CreatePdfDoc(new ImagesForPDF(path, "Ðóññêàÿ ëèòåðàòóðà", files))) MessageBox.Show("Óñïåõ!");
|
||||
else MessageBox.Show("Îøèáêà, ïðîâåðüòå êîíñîëü");
|
||||
}
|
||||
|
||||
private void buttonTestPdfTable_Click(object sender, EventArgs e)
|
||||
{
|
||||
List<BookInfo> books = new List<BookInfo>
|
||||
{
|
||||
new BookInfo("Ýêñìî", "Íèêîëàé", "Ãîãîëü", "1809-1852", "̸ðòâûå äóøè"),
|
||||
new BookInfo("Òðèóìô", "Èâàí", "Òóðãåíåâ", "1818-1883", "Îòöû è äåòè"),
|
||||
new BookInfo("Ýêñìî", "Äæîðäæ", "Îðóýëë", "1903-1950", "1984"),
|
||||
new BookInfo("ÀÑÒ", "Äæîàíà", "Ðîóëèíã", "1965 - í.â.", "Ãàððè Ïîòòåð")
|
||||
};
|
||||
|
||||
List<(int, int)> merges = new List<(int, int)>();
|
||||
merges.Add((2, 4));
|
||||
List<int> heights = new List<int> {10, 40, 20, 10, 10, 30, 10, 10, 10, 15, 24 };
|
||||
|
||||
string path = "C:\\Users\\xarla\\OneDrive\\Äîêóìåíòû\\test.pdf";
|
||||
|
||||
List<(bool, string)> headers = new List<(bool, string)> { (false, "id"), (false, "Ðåäàêöèÿ"),
|
||||
(true, "Àâòîð"), (false, "Èìÿ"),
|
||||
(false, "Ôàìèëèÿ"), (false, "Ãîäû æèçíè"),
|
||||
(false, "Íàçâàíèå êíèãè") };
|
||||
|
||||
if (pdfTable1.createTable(path, "test2", merges, heights, headers, books)) MessageBox.Show("Óñïåõ");
|
||||
}
|
||||
}
|
||||
}
|
@ -63,4 +63,7 @@
|
||||
<metadata name="openFileDialog1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>150, 17</value>
|
||||
</metadata>
|
||||
<metadata name="pdfTable1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>317, 17</value>
|
||||
</metadata>
|
||||
</root>
|
36
ViewComponents/NotVisualComponents/PdfTable.Designer.cs
generated
Normal file
36
ViewComponents/NotVisualComponents/PdfTable.Designer.cs
generated
Normal file
@ -0,0 +1,36 @@
|
||||
namespace ViewComponents.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
|
||||
}
|
||||
}
|
170
ViewComponents/NotVisualComponents/PdfTable.cs
Normal file
170
ViewComponents/NotVisualComponents/PdfTable.cs
Normal file
@ -0,0 +1,170 @@
|
||||
using MigraDoc.DocumentObjectModel;
|
||||
using MigraDoc.DocumentObjectModel.Tables;
|
||||
using MigraDoc.Rendering;
|
||||
using PdfSharp.Pdf.Content.Objects;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ViewComponents.NotVisualComponents
|
||||
{
|
||||
public partial class PdfTable : Component
|
||||
{
|
||||
public PdfTable()
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public PdfTable(IContainer container)
|
||||
{
|
||||
container.Add(this);
|
||||
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
public bool createTable<T>(string filepath, string header, List<(int, int)> merges, List<int> heights, List<(bool, string)> headers, List<T> items)
|
||||
{
|
||||
//проверки
|
||||
if (merges.Count == 0 || heights.Count == 0 || headers.Count == 0 || items.Count == 0) throw new ArgumentException("Недостаточно данных");
|
||||
int[] cellsArray = new int[heights.Count];
|
||||
foreach (var merge in 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("Объединения заходят друг на друга");
|
||||
}
|
||||
|
||||
//создание документа
|
||||
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 = "Times New Roman";
|
||||
style.Font.Size = 12;
|
||||
|
||||
//добавление заголовка
|
||||
var section = _document.AddSection();
|
||||
var paragraph = section.AddParagraph(header);
|
||||
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 < items.Count + 2; i++)
|
||||
{
|
||||
column = table.AddColumn();
|
||||
column.Format.Alignment = ParagraphAlignment.Center;
|
||||
}
|
||||
|
||||
// создание шапки и заполнение контентом
|
||||
|
||||
int mergeRange = 0; //размерность слияния
|
||||
int mergeIndex = 0; //стартовый индекс начала слияния
|
||||
Row row;
|
||||
for (int i = 0; i < headers.Count; i++)
|
||||
{
|
||||
//если элемент шапки не группируется по строкам
|
||||
if (headers[i].Item1 == false)
|
||||
{
|
||||
//стилизация ячейки
|
||||
row = table.AddRow();
|
||||
row.Height = heights[i];
|
||||
row.Format.Font.Bold = true;
|
||||
row.Format.Alignment = ParagraphAlignment.Center;
|
||||
row.Cells[0].AddParagraph(headers[i].Item2);
|
||||
row.Cells[0].VerticalAlignment = VerticalAlignment.Center;
|
||||
row.Cells[0].MergeRight = 1;
|
||||
|
||||
AddTheContent<T>(items, table, row.Index, 2);
|
||||
|
||||
mergeIndex++;
|
||||
}
|
||||
|
||||
//если элемент шапки группируются по строкам
|
||||
if (headers[i].Item1 == true)
|
||||
{
|
||||
mergeRange = merges.Find(x => x.Item1 == mergeIndex).Item2 - mergeIndex;
|
||||
mergeIndex = merges.Find(x => x.Item1 == mergeIndex).Item2 + 1;
|
||||
|
||||
//стилизация ячейки. в этом блоке кода (до цикла) создаётся объединяющая ячейка
|
||||
row = table.AddRow();
|
||||
row.Height = heights[i];
|
||||
row.Format.Alignment = ParagraphAlignment.Center;
|
||||
row.Format.Font.Bold = true;
|
||||
row.Cells[0].AddParagraph(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(headers[i].Item2);
|
||||
AddTheContent<T>(items, table, row.Index, 2);
|
||||
row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
|
||||
row = table.AddRow();
|
||||
row.Height = heights[i];
|
||||
row.Format.Font.Bold = true;
|
||||
row.Format.Alignment = ParagraphAlignment.Center;
|
||||
}
|
||||
|
||||
i++;
|
||||
row.Cells[1].AddParagraph(headers[i].Item2);
|
||||
AddTheContent<T>(items, table, row.Index, 2);
|
||||
row.Cells[1].VerticalAlignment = VerticalAlignment.Center;
|
||||
}
|
||||
}
|
||||
|
||||
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
|
||||
renderer.Document = _document;
|
||||
renderer.RenderDocument();
|
||||
renderer.PdfDocument.Save(filepath);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
//метод заполнения таблицы контентом, заполнение происходит построчно.
|
||||
public void AddTheContent<T>(List<T> items, Table table, 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();
|
||||
r.Cells[cell_index + i].AddParagraph(fields[row_index-1].GetValue(item).ToString());
|
||||
r.Cells[cell_index + i].VerticalAlignment = VerticalAlignment.Center;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user