EvaluationReportBaseSection.cs 7.6 KB
Newer Older
1
2
3
4
5
6
7
8
using iText.IO.Image;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Action;
using iText.Layout;
using iText.Layout.Borders;
using iText.Layout.Element;
using iText.Layout.Properties;
9
10
using PDFGenerator.Models.EvaluationReport;
using PDFGenerator.Renderers;
11
12
13
using PDFGenerator.Utilities;
using System.Collections.Generic;
using System.IO;
14
using System.Text.RegularExpressions;
15
16
using static PDFGenerator.Utilities.Globals;

17
namespace PDFGenerator.DocumentStructures.EvaluationReport
18
{
19
    public abstract class EvaluationReportBaseSection : BaseSection
20
21
22
23
24
25
    {
        protected PdfOutline RootOutline { get; }
        protected Bookmarks Bookmarks { get; }
        protected TableOfContents TableOfContents { get; }
        protected static Text NewLine { get; } = new Text("\n");

26
        public EvaluationReportBaseSection(Document document, Bookmarks bookmarks, TableOfContents tableOfContents) : base(document)
27
28
29
30
        {
            Bookmarks = bookmarks;
            TableOfContents = tableOfContents;

Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
31
            // get root outline from the PdfDocument: false indicates iText does not need to update the outlines.
32
33
34
35
36
37
38
39
40
41
42
            RootOutline = Document.GetPdfDocument().GetOutlines(false);
        }

        /// <summary>
        /// Renders the content in each section.
        /// </summary>
        public abstract void Render();

        /// <summary>
        /// Gets the current page.
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
43
        /// <returns>The current page.</returns>
44
45
46
47
48
49
50
51
        protected int GetCurrentPage()
        {
            return Document.GetPdfDocument().GetNumberOfPages();
        }

        /// <summary>
        /// Resizes image to fit page size.
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
52
53
        /// <param name="image">Image to be resized.</param>
        /// <returns>The resized image.</returns>
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
        protected 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>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
69
70
71
72
        /// Adds upload files directly to the document if they are images.
        /// Uploads consisting of PDF files are added to the available custom uploads to be rendered as attachments in appendix
        /// and links are added to the document referring to them instead.
        /// If the custom uploads are neither PDF files nor image files an exception is thrown.
73
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
74
75
        /// <param name="uploads">New custom uploads to be considered.</param>
        /// <param name="customUploads">Already available custom uploads.</param>
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
        protected void AddCustomUploads(CustomUploads uploads, Dictionary<string, byte[]> customUploads)
        {
            if (uploads.Files == null)
            {
                if (!string.IsNullOrEmpty(uploads.Paragraph))
                {
                    Document.Add(ParagraphFactory.GetStandardParagraph(uploads.Paragraph));
                    return;
                }

                return;
            }

            bool imagesAvailable = false;
            foreach (KeyValuePair<string, byte[]> file in uploads.Files)
            {
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
92
93
                // only accept files in image or PDF format, otherwise an exception is thrown below

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
                // firstly, check if file is a valid image
                if (ImageDataFactory.IsSupportedType(file.Value))
                {
                    ImageData imageData = ImageDataFactory.Create(file.Value);
                    Image image = new Image(imageData)
                        .SetMarginTop(10f)
                        .SetHorizontalAlignment(HorizontalAlignment.CENTER)
                        .SetMarginBottom(15f);

                    AddScaledImage(image);
                    imagesAvailable = true;

                    continue;
                }

Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
109
                // secondly, if data does not correspond to a PDF file, an exception is thrown
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
                new PdfReader(new MemoryStream(file.Value));

                if (!customUploads.ContainsKey(file.Key))
                {
                    customUploads.Add(file.Key, file.Value);
                }

                // ensure that the sentence is only written once
                if (customUploads.Count == 1)
                {
                    Document.Add(ParagraphFactory.GetStandardParagraph("Weitere Dokumente siehe Anhang."));
                }

                Document.Add(
                    ParagraphFactory.GetStandardParagraph(file.Key)
                    .SetMarginTop(-2f)
                    .SetAction(PdfAction.CreateGoTo(file.Key))
                );
            };

            if (!imagesAvailable && !string.IsNullOrEmpty(uploads.Paragraph))
            {
                Document.Add(ParagraphFactory.GetStandardParagraph(uploads.Paragraph));
            }
        }

        /// <summary>
        /// Adds paragraph above the table.
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
139
        /// <param name="table">The table on which the paragraph is added.</param>
140
        /// <param name="text">The paragraphs content.</param>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
141
142
        /// <param name="header">Flag indicating whether the content is a table header.</param>
        /// <param name="style">Given style for paragraph.</param>
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
        protected void AddParagraphWithLeadingToTable(Table table, string text, bool header, Style style = null)
        {
            Cell cell = new Cell().SetBorder(Border.NO_BORDER);
            Paragraph p;

            if (header)
            {
                cell.SetPaddingTop(12.5f).SetPaddingBottom(7f);
                p = ParagraphFactory.GetTableHeaderParagraph(text, style);
            }
            else
            {
                cell.SetPaddingTop(0f);
                p = ParagraphFactory.GetStandardParagraph(text);
            }
            p.SetKeepTogether(true);

            cell.Add(p);
            table.AddCell(cell);
        }

        /// <summary>
        /// Changes the page orientation.
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
167
        /// <param name="orientation">Orientation to change to.</param>
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
        protected void SetPageOrientation(Orientation orientation)
        {
            if (orientation == Orientation.Landscape)
            {
                Document.GetPdfDocument().SetDefaultPageSize(PageSize.A4.Rotate());
                return;
            }

            Document.GetPdfDocument().SetDefaultPageSize(PageSize.A4);
        }

        /// <summary>
        /// Adds line break to document.
        /// </summary>
        protected void AddLineBreak()
        {
            Document.Add(ParagraphFactory.GetTableHeaderParagraph(string.Empty));
        }

187
        /// <summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
188
189
        /// Prevents the default trim of leading whitespaces in the string
        /// and immediately after a linebreak on iText7 by adding a NULL character ('\u0000')
190
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
191
192
        /// <param name="text">Text which leading whitespaces to be preserved.</param>
        /// <returns>Text with preserved leading whitespaces.</returns>
193
194
195
196
197
        protected string PreserveLeadingSpaces(string text)
        {
            return "\u0000" + Regex.Replace(text, @"\n", "\n\u0000");
        }

198
199
200
        /// <summary>
        /// Adds scaled image to document.
        /// </summary>
Sebastian Drenckberg's avatar
Sebastian Drenckberg committed
201
        /// <param name="image">Image to add do document.</param>
202
203
204
205
206
207
        private void AddScaledImage(Image image)
        {
            Document.Add(GetScaledImage(image));
        }
    }
}