Chapter.cs 8.87 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
using iText.IO.Image;
using iText.Kernel.Geom;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Layout;
using iText.Layout.Properties;
using PDFGenerator.Models.FactSheet;
using PDFGenerator.Utilities;
using System.Collections.Generic;
using System.Linq;

namespace PDFGenerator.DocumentStructures.FactSheet
{
    public class Chapter : FactSheetBaseSection
    {
        private PDFChapter PDFChapter { get; set; }
        private Headline CommonMessage { get; }
        private Table Table { get; set; }
        private string[] ItalicStyleForExpressions { get; } = new string[] { "kohorte" };

        // control variables
        private int ReportSectionElementCounter { get; set; }

        public Chapter(Headline commonMessage, Document document) : base(document)
        {
            CommonMessage = commonMessage;
        }

        /// <summary>
        /// Updates the chapter to render.
        /// </summary>
        /// <param name="chapter"></param>
        public void UpdateChapter(PDFChapter chapter)
        {
            PDFChapter = chapter;
        }

        /// <summary>
        /// Renders the content for a chapter.
        /// </summary>
        public void Render()
        {
            // add page break at the chapter begin
            AddPageBreak();

            Table = new Table(1, false)
                .UseAllAvailableWidth().SetKeepTogether(false);

            AddParagrpahToTable(ParagraphFactory.GetCustomParagraph(PDFChapter.Title.Name, HeadlineLevel[PDFChapter.Title.Level], 5.0f, 0, 1.12f));

            for (int i = 0; i < PDFChapter.ReportSections.Count; i++)
            {
                ReportSectionElementCounter = 0;
                bool reportSectionRendered = false;
                while (!reportSectionRendered)
                {
                    if (PDFChapter.ReportSections[i].Headlines != null)
                    {
                        foreach (Headline headline in PDFChapter.ReportSections[i].Headlines)
                        {
                            // give hihgher space in between report sections, if the report section is neither the first nor the current position is on the page top
                            float spacinfBefore = i == 0 || IsCurrentPositionOnPageTop() || headline.Name != PDFChapter.ReportSections[i].Headlines[0].Name ? 3.0f : 15.0f;

                            bool isItalic = ItalicStyleForExpressions.Any(expression => headline.Name.ToLower().Contains(expression));

                            AddParagrpahToTable(ParagraphFactory.GetCustomParagraph(headline.Name, HeadlineLevel[headline.Level], spacinfBefore, 0, 1.1f, isItalic));
                        }
                    }

                    if (PDFChapter.ReportSections[i].Header != null)
                    {
                        AddParagrpahToTable(
                            ParagraphFactory.GetCustomParagraph(PDFChapter.ReportSections[i].Header.Name, HeadlineLevel[PDFChapter.ReportSections[i].Header.Level], 9.0f, 0, 1.12f)
                            .SetTextAlignment(TextAlignment.CENTER)
                        );
                    }

                    if (PDFChapter.ReportSections[i].Images != null)
                    {
                        if (!AddImagesToTable(PDFChapter.ReportSections[i].Images))
                        {
                            MoveNextReportSectionToNextPage();
                            continue;
                        }
                    }
                    else
                    {
                        // display the no data available message
                        AddParagrpahToTable(ParagraphFactory.GetCustomParagraph(CommonMessage.Name, HeadlineLevel[CommonMessage.Level], 8.0f, 11.0f, 1.12f));
                    }

                    reportSectionRendered = true;
                }
            }

            Document.Add(Table);
        }

        /// <summary>
        /// Adds a single report.
        /// </summary>
        /// <param name="images">List of images representing the report.</param>
        private bool AddImagesToTable(List<byte[]> images)
        {
            ImageData imageData;
            Image image;

            for (int i = 0; i < images.Count; i++)
            {
                float currentHeight = RemainingTableHeight();

                imageData = ImageDataFactory.Create(images[i]);
                image = new Image(imageData);

                Cell cell = new Cell()
                .Add(GetScaledImage(image))
                .SetBorder(Border.NO_BORDER)
                .SetMargin(0)
                .SetPadding(0)
                .SetPaddingTop(6f);

                Table.AddCell(cell);

                ReportSectionElementCounter++;
                float nextHeight = RemainingTableHeight();
                if (currentHeight == nextHeight)
                {
                    if (i == 0)
                    {
                        RemoveReportSectionElementsFromTable();
                        return false;
                    }

                    ReportSectionElementCounter = 1;
                    RemoveReportSectionElementsFromTable();
                    MoveNextReportSectionToNextPage();
                    i--;
                }
            }

            return true;
        }

        /// <summary>
        /// Resizes image to fit page size.
        /// </summary>
        /// <param name="image">Image to be resized.</param>
        /// <returns>The resized image.</returns>
        private Image GetScaledImage(Image image)
        {
            PageSize pageSize = GetPageSize();
            float maxWidth = pageSize.GetWidth() - Document.GetLeftMargin() - Document.GetRightMargin();
            float maxHeight = pageSize.GetHeight() - Document.GetTopMargin() - Document.GetBottomMargin();

            if (image.GetImageWidth() > maxWidth || image.GetImageHeight() > maxHeight)
            {
                return image.ScaleToFit(maxWidth, maxHeight);
            }

            return image;
        }

        /// <summary>
        /// Creates a cell with the given paragraph and adds it to the table.
        /// </summary>
        /// <param name="paragraph">input paragraph to be added.</param>
        private void AddParagrpahToTable(Paragraph paragraph)
        {
            Cell cell = new Cell()
                .SetBorder(Border.NO_BORDER)
                .SetPadding(0);

            cell.Add(paragraph);
            Table.AddCell(cell);

            ReportSectionElementCounter++;
        }

        /// <summary>
        /// Writes the current table content in the document and sets a page break, 
        /// so that the next report section is written on the following page.
        /// </summary>
        private void MoveNextReportSectionToNextPage()
        {
            Document.Add(Table);
            AddPageBreak();
            Table = new Table(1, false)
            .UseAllAvailableWidth().SetKeepTogether(false);
        }

        /// <summary>
        /// Gets the vertical positon, from which there is still available place to write on the current page.
        /// </summary>
        /// <returns>The current available vertical space on the page.</returns>
        private float RemainingTableHeight()
        {
            // document area
            Rectangle documentBox = Document.GetRenderer().GetCurrentArea().GetBBox();

            // to get the effective table width as if it was drawn on a page already, one needs to create a viewport with an area equivalent to the document area, sufficient to contain 
            // the table elements for an entire page;
            // one needs to get the subtree of renderers representing the table element and all its children and then layout it in the viewport; the maximum height of the viewport layoutarea 
            // is set to the document height (except margins)
            LayoutResult result = Table.CreateRendererSubTree().SetParent(Document.GetRenderer())
                .Layout(new LayoutContext(new LayoutArea(1, new Rectangle(0, 0, documentBox.GetWidth(), documentBox.GetHeight()))));

            return result.GetOccupiedArea().GetBBox().GetY();
        }

        /// <summary>
        /// Checks, if the current position is on the page top.
        /// </summary>
        /// <returns>True, if the condition is met.</returns>
        private bool IsCurrentPositionOnPageTop()
        {
            return RemainingTableHeight() == Document.GetRenderer().GetCurrentArea().GetBBox().GetHeight();
        }

        /// <summary>
        /// Removes some oder all report section elements from the table, depending
        /// on the current report section element counter.
        /// </summary>
        private void RemoveReportSectionElementsFromTable()
        {
            for (int i = 0; i < ReportSectionElementCounter; i++)
            {
                Table.GetChildren().RemoveAt(Table.GetChildren().Count - 1);
            }
            ReportSectionElementCounter = 0;
        }
    }
}