diff --git a/TestView/BookInfo.cs b/TestView/BookInfo.cs new file mode 100644 index 0000000..ac56c7f --- /dev/null +++ b/TestView/BookInfo.cs @@ -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; + } + } +} diff --git a/TestView/Form1.Designer.cs b/TestView/Form1.Designer.cs index 47e9a48..cb54318 100644 --- a/TestView/Form1.Designer.cs +++ b/TestView/Form1.Designer.cs @@ -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; } } \ No newline at end of file diff --git a/TestView/Form1.cs b/TestView/Form1.cs index ec3dded..cb110de 100644 --- a/TestView/Form1.cs +++ b/TestView/Form1.cs @@ -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 books = new List + { + 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 heights = new List {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(""); + } } } \ No newline at end of file diff --git a/TestView/Form1.resx b/TestView/Form1.resx index c599dda..dc63100 100644 --- a/TestView/Form1.resx +++ b/TestView/Form1.resx @@ -63,4 +63,7 @@ 150, 17 + + 317, 17 + \ No newline at end of file diff --git a/ViewComponents/NotVisualComponents/PdfTable.Designer.cs b/ViewComponents/NotVisualComponents/PdfTable.Designer.cs new file mode 100644 index 0000000..2e0423e --- /dev/null +++ b/ViewComponents/NotVisualComponents/PdfTable.Designer.cs @@ -0,0 +1,36 @@ +namespace ViewComponents.NotVisualComponents +{ + partial class PdfTable + { + /// + /// Обязательная переменная конструктора. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Освободить все используемые ресурсы. + /// + /// истинно, если управляемый ресурс должен быть удален; иначе ложно. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Код, автоматически созданный конструктором компонентов + + /// + /// Требуемый метод для поддержки конструктора — не изменяйте + /// содержимое этого метода с помощью редактора кода. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion + } +} diff --git a/ViewComponents/NotVisualComponents/PdfTable.cs b/ViewComponents/NotVisualComponents/PdfTable.cs new file mode 100644 index 0000000..69fc980 --- /dev/null +++ b/ViewComponents/NotVisualComponents/PdfTable.cs @@ -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(string filepath, string header, List<(int, int)> merges, List heights, List<(bool, string)> headers, List 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(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(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(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(List items, Table table, int row_index, int cell_index) + { + foreach (Row r in table.Rows) + { + for (int i = 0; i