-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathParagraphItem.cs
More file actions
544 lines (468 loc) · 22.6 KB
/
Copy pathParagraphItem.cs
File metadata and controls
544 lines (468 loc) · 22.6 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
using EPPlus.Fonts.OpenType;
using EPPlus.Fonts.OpenType.Integration;
using EPPlus.Fonts.OpenType.TextShaping;
using EPPlus.Fonts.OpenType.Utils;
using EPPlus.Graphics;
using EPPlusImageRenderer;
using EPPlusImageRenderer.RenderItems;
using EPPlusImageRenderer.Utils;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Drawing.Theme;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using OfficeOpenXml.Interfaces.Drawing.Text;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using EPPlusColorConverter = OfficeOpenXml.Utils.TypeConversion.ColorConverter;
namespace EPPlus.Export.ImageRenderer.RenderItems.Shared
{
internal abstract class ParagraphItem : RenderItem
{
TextLayoutEngine _layout;
double _leftMargin;
double _rightMargin;
eDrawingTextLineSpacing _lsType;
double _lineSpacingAscendantOnly;
double? _lsMultiplier = null;
internal bool IsFirstParagraph { get; private set; }
List<string> _paragraphLines = new List<string>();
protected List<string> _textRunDisplayText = new List<string>();
TextFragmentCollectionSimple _textFragments;
List<EPPlus.Fonts.OpenType.Integration.TextFragment> _newTextFragments;
internal protected MeasurementFont _paragraphFont;
internal TextBodyItem ParentTextBody { get; set; }
internal double ParagraphLineSpacing { get; private set; }
internal eTextAlignment HorizontalAlignment { get; private set; }
internal List<TextRunItem> Runs { get; set; } = new List<TextRunItem>();
internal bool DisplayBounds { get; set; } = false;
private double? _centerAdjustment = null;
internal List<double> SpaceWidthsPerLine = new List<double>();
public ParagraphItem(TextBodyItem textBody, DrawingBase renderer, BoundingBox parent) : base(renderer, parent)
{
ParentTextBody = textBody;
Bounds.Name = "Paragraph";
var defaultFont = new MeasurementFont { FontFamily = "Aptos Narrow", Size = 11, Style = MeasurementFontStyles.Regular };
_paragraphFont = defaultFont;
_layout = OpenTypeFonts.GetTextLayoutEngineForFont(defaultFont);
ParagraphLineSpacing = GetParagraphLineSpacingInPoints(100, (TextShaper)OpenTypeFonts.GetShaperForFont(defaultFont), defaultFont.Size);
}
public ParagraphItem(TextBodyItem textBody, DrawingBase renderer, BoundingBox parent, ExcelDrawingParagraph p, string textIfEmpty = null) : base(renderer, parent)
{
ParentTextBody = textBody;
IsFirstParagraph = p == p._paragraphs[0];
if (p.DefaultRunProperties.Fill != null && p.DefaultRunProperties.Fill.IsEmpty == false)
{
if (IsFirstParagraph)
{
if (p.DefaultRunProperties.Fill != null)
{
SetDrawingPropertiesFill(p.DefaultRunProperties.Fill, null);
}
}
else
{
//Drawingproperties has fallback to firstDefault but excel does not display it so we should not either.
if (p.DefaultRunProperties != p._paragraphs.FirstDefaultRunProperties)
{
SetDrawingPropertiesFill(p.DefaultRunProperties.Fill, null);
}
else
{
var fc = EPPlusColorConverter.GetThemeColor(DrawingRenderer.Theme.ColorScheme.Light1);
fc = ColorUtils.GetAdjustedColor(PathFillMode.Norm, fc);
FillColor = "#" + fc.ToArgb().ToString("x8").Substring(2);
//Use shape fill somehow
//Maybe use a name property for fallback theme accent1 color?
}
}
}
else
{
if (p._paragraphs.FirstDefaultRunProperties != null && p._paragraphs.FirstDefaultRunProperties.Fill != null && p._paragraphs.FirstDefaultRunProperties.Fill.IsEmpty == false)
{
var fill = p._paragraphs.FirstDefaultRunProperties.Fill;
SetDrawingPropertiesFill(fill, null);
}
}
//---Initialize Bounds / Margins-- -
Bounds.Name = "Paragraph";
var indent = 48 * p.IndentLevel;
_leftMargin = p.LeftMargin + p.Indent + indent;
_rightMargin = p.RightMargin;
_leftMargin = _leftMargin.PixelToPoint();
_rightMargin = _rightMargin.PixelToPoint();
HorizontalAlignment = p.HorizontalAlignment;
_leftMargin = _leftMargin.PixelToPoint();
_rightMargin = _rightMargin.PixelToPoint();
HorizontalAlignment = p.HorizontalAlignment;
if (ParentTextBody.AutoSize == false)
{
Bounds.Left = 0;
Bounds.Width = ParentTextBody.MaxWidth;
//Left is equal to left Paragraph margin
//Textbody or Textbox are assumed to handle shape/chart margins
//Paragraph handles only indentations/margins that is applied ON TOP of those margins
//Paragraph left is the exact position where the text itself starts on the left
if (HorizontalAlignment != eTextAlignment.Center)
{
Bounds.Left = GetAlignmentHorizontal(HorizontalAlignment);
}
else
{
//Center is a bit strange the bounds really are the same as left or right aligned
//It doesn't truly matter as only left min and right max play a role
Bounds.Left = GetAlignmentHorizontal(eTextAlignment.Left);
_centerAdjustment = GetAlignmentHorizontal(HorizontalAlignment);
}
Bounds.Width = parent.Width - _rightMargin - _leftMargin;
}
//---Initialize / calculate lines and runs---
//measurer must be set before AddLinesAndRichText
_paragraphFont = p.DefaultRunProperties.GetMeasureFont();
//---Get measurer---
_layout = OpenTypeFonts.GetTextLayoutEngineForFont(_paragraphFont);
//---Calculate linespacing---
int numLines = _paragraphLines.Count;
_lsType = p.LineSpacing.LineSpacingType;
ParagraphLineSpacing = GetParagraphLineSpacingInPoints(p.LineSpacing.Value,
(TextShaper) OpenTypeFonts.GetShaperForFont(_paragraphFont),
_paragraphFont.Size);
AddLinesAndTextRuns(p, textIfEmpty);
}
private double GetParagraphLineSpacingInPoints(double spacingValue, TextShaper fmExact, float fontSize)
{
if (_lsType == eDrawingTextLineSpacing.Exactly)
{
if (IsFirstParagraph)
{
_lineSpacingAscendantOnly = spacingValue;
}
return spacingValue;
}
else
{
var multiplier = (spacingValue / 100);
_lsMultiplier = multiplier;
if (IsFirstParagraph)
{
_lineSpacingAscendantOnly = multiplier * fmExact.GetAscentInPoints(fontSize);
}
return multiplier * fmExact.GetLineHeightInPoints(fontSize);
}
}
internal protected TextRunItem AddRenderItemTextRun(ExcelParagraphTextRunBase origTxtRun, string displayText, double startingX)
{
var targetTxtRun = CreateTextRun(origTxtRun, Bounds, displayText);
targetTxtRun.Bounds.Left = startingX;
Runs.Add(targetTxtRun);
return targetTxtRun;
}
public void AddText(string text, double prevWidth)
{
var container = CreateTextRun(_paragraphFont, Bounds, text);
Runs.Add(container);
container.Bounds.Name = $"Container{Runs.Count}";
container.Bounds.Left = prevWidth;
}
public void AddText(string text, ExcelTextFont font, bool isOld)
{
var mf = font.GetMeasureFont();
var measurer = OpenTypeFonts.GetTextLayoutEngineForFont(mf);
var displayText = measurer.WrapText(text, mf.Size, ParentTextBody.MaxWidth);
var container = CreateTextRun(text, font, Bounds, string.Join("\r\n", displayText.ToArray()));
//container.BaseLineSpacing = _lineSpacingAscendantOnly;
//container.LineSpacingPerNewLine = _lsMultiplier.Value * _measurer.GetSingleLineSpacing().PointToPixel(true);
Runs.Add(container);
Bounds.Width = container.Bounds.Width + 0.001; //TODO: fix for equal width issue
container.Bounds.Name = $"Container{Runs.Count}";
}
public void AddText(string text, ExcelTextFont font, double prevWidth)
{
var mf = font.GetMeasureFont();
var measurer = OpenTypeFonts.GetTextLayoutEngineForFont(mf);
//var displayText = measurer.MeasureAndWrapTextLines(text, font.GetMeasureFont(), ParentTextBody.MaxWidth);
var container = CreateTextRun(text, font, Bounds, text);
//container.BaseLineSpacing = _lineSpacingAscendantOnly;
//container.LineSpacingPerNewLine = _lsMultiplier.Value * _measurer.GetSingleLineSpacing().PointToPixel(true);
Runs.Add(container);
//Bounds.Width = container.Bounds.Width + 0.001; //TODO: fix for equal width issue
container.Bounds.Name = $"Container{Runs.Count}";
container.Bounds.Left = prevWidth;
}
void GenerateTextFragments(string text)
{
_newTextFragments = new List<TextFragment>();
if (string.IsNullOrEmpty(text) == false)
{
var currentFrag = new TextFragment() { Text = text, Font = _paragraphFont};
_newTextFragments.Add(currentFrag);
}
}
/// <summary>
/// Log linebreak positions and sizes of the runs
/// So that we can easily know what textfragment is on what line and what size it has later
/// </summary>
/// <param name="runs"></param>
void GenerateTextFragments(ExcelDrawingTextRunCollection runs)
{
List<string> runContents = new List<string>();
List<float> fontSizes = new List<float>();
List<MeasurementFont> fonts = new List<MeasurementFont>();
for (int i = 0; i < runs.Count(); i++)
{
var txtRun = runs[i];
var runFont = txtRun.GetMeasurementFont();
fonts.Add(runFont);
fonts.Add(runFont);
runContents.Add(txtRun.Text);
fontSizes.Add(runFont.Size);
}
//_textFragments = new TextFragmentCollection(runContents, fontSizes);
_newTextFragments = new List<EPPlus.Fonts.OpenType.Integration.TextFragment>();
for (int i = 0; i < runContents.Count(); i++)
{
if (string.IsNullOrEmpty(runContents[i]) == false)
{
var currentFrag = new TextFragment() { Text = runContents[i], Font = fonts[i] };
_newTextFragments.Add(currentFrag);
}
}
}
internal void AddLinesAndTextRuns(string textIfEmpty)
{
GenerateTextFragments(textIfEmpty);
var lines = new List<TextLineSimple>();
var measurer = OpenTypeFonts.GetTextLayoutEngineForFont(_paragraphFont);
var maxWidth = ParentTextBody.MaxWidth + 0.001; //TODO: fix for equal width issue;
List<TextFragment> textFragments = new List<TextFragment>();
var fragment = new TextFragment() { Font = _paragraphFont, Text = textIfEmpty };
textFragments.Add(fragment);
lines = measurer.WrapRichTextLines(textFragments, maxWidth);
bool lineSpacingIsExact = _lsMultiplier.HasValue == false;
double runLineSpacing = 0;
double greatestWidth = 0;
//In points
double lastDescent = 0;
if (lines != null && lines.Count != 0)
{
//This could be moved into a textLines collection class
//START
var idxOfLargestLine = 0;
double widthOfLargestLine = lines[0].Width;
//SpaceWidthsPerLine.Add(lines[0].lastFontSpaceWidth);
for (int i = 1; i < lines.Count; i++)
{
if (lines[i].Width > widthOfLargestLine)
{
var ctrLineWidth = lines[i].GetWidthWithoutTrailingSpaces();
SpaceWidthsPerLine.Add(lines[i].lastFontSpaceWidth);
widthOfLargestLine = ctrLineWidth;
idxOfLargestLine = i;
}
}
//END
if (HorizontalAlignment == eTextAlignment.Center && ParentTextBody.AutoSize)
{
//Bounds of the paragraph should be bounds of the text itself.
//Therefore we must know the starting point to set accurate left and offset from left.
Bounds.Left = _centerAdjustment.Value - (widthOfLargestLine / 2);
}
foreach (var line in lines)
{
double prevWidth = 0;
if (HorizontalAlignment == eTextAlignment.Center)
{
var ctrLineWidth = line.GetWidthWithoutTrailingSpaces();
prevWidth = (widthOfLargestLine - ctrLineWidth) / 2;
}
else if (HorizontalAlignment == eTextAlignment.Right)
{
//Note that the actual bounds with the space will be outside max bounds.
//This appears to be how excel does it
var ctrLineWidth = line.GetWidthWithoutTrailingSpaces();
prevWidth = widthOfLargestLine - ctrLineWidth;
}
if (lineSpacingIsExact == false)
{
runLineSpacing += line.LargestAscent + lastDescent;
}
else
{
runLineSpacing += ParagraphLineSpacing;
}
if (line.GetWidthWithoutTrailingSpaces() > greatestWidth)
{
greatestWidth = line.GetWidthWithoutTrailingSpaces();
}
foreach (var lineFragment in line.LineFragments)
{
var displayText = lineFragment.Text;
if (string.IsNullOrEmpty(textIfEmpty) == false)
{
AddText(displayText, prevWidth);
}
TextRunItem runItem = Runs.Last();
runItem.YPosition = runLineSpacing;
runItem.Bounds.Width = lineFragment.Width;
prevWidth += lineFragment.Width;
}
lastDescent = line.LargestDescent;
}
}
Bounds.Height = runLineSpacing + lastDescent;
Bounds.Width = greatestWidth;
}
private void AddLinesAndTextRuns(ExcelDrawingParagraph p, string textIfEmpty)
{
//Log line positions and run sizes
GenerateTextFragments(p.TextRuns);
var lines = new List<TextLineSimple>();
//In points
double lastDescent = 0;
bool lineSpacingIsExact = _lsMultiplier.HasValue == false;
double runLineSpacing = 0;
double greatestWidth = 0;
if (p.TextRuns.Count == 0 && string.IsNullOrEmpty(textIfEmpty) == false)
{
var font = p.DefaultRunProperties.GetMeasureFont();
var measurer = OpenTypeFonts.GetTextLayoutEngineForFont(font);
var maxWidth = ParentTextBody.MaxWidth + 0.001; //TODO: fix for equal width issue;
lines = measurer.WrapRichTextLines(textIfEmpty, font, maxWidth);
//Bounds.Width = maxWidth;
if (HorizontalAlignment != eTextAlignment.Center)
{
Bounds.Left = GetAlignmentHorizontal(HorizontalAlignment);
}
else
{
Bounds.Left = GetAlignmentHorizontal(eTextAlignment.Left);
_centerAdjustment = GetAlignmentHorizontal(HorizontalAlignment);
}
}
else
{
lines = WrapToSimpleTextLines(p);
}
if (lines != null && lines.Count != 0)
{
//This could be moved into a textLines collection class
//START
var idxOfLargestLine = 0;
double widthOfLargestLine = lines[0].GetWidthWithoutTrailingSpaces();
//SpaceWidthsPerLine.Add(lines[0].lastFontSpaceWidth);
for (int i = 1; i < lines.Count; i++)
{
if (lines[i].Width > widthOfLargestLine)
{
var ctrLineWidth = lines[i].GetWidthWithoutTrailingSpaces();
SpaceWidthsPerLine.Add(lines[i].lastFontSpaceWidth);
widthOfLargestLine = ctrLineWidth;
idxOfLargestLine = i;
}
}
//END
if (ParentTextBody.AutoSize)
{
//Bounds of the paragraph should be bounds of the text itself.
//Therefore we must know the starting point to set accurate left and offset from left.
Bounds.Left = 0;
}
foreach (var line in lines)
{
double prevWidth = 0;
if (HorizontalAlignment == eTextAlignment.Center)
{
var ctrLineWidth = line.GetWidthWithoutTrailingSpaces();
//Calculate difference in widths and split to get offset between leftmost position and current line
prevWidth = (widthOfLargestLine - ctrLineWidth) / 2;
}
else if (HorizontalAlignment == eTextAlignment.Right)
{
//Note that the actual bounds with the space will be outside max bounds.
//This appears to be how excel does it
var ctrLineWidth = line.GetWidthWithoutTrailingSpaces();
prevWidth = widthOfLargestLine - ctrLineWidth;
}
if (lineSpacingIsExact == false)
{
runLineSpacing += line.LargestAscent + lastDescent;
}
else
{
runLineSpacing += ParagraphLineSpacing;
}
if (line.GetWidthWithoutTrailingSpaces() > greatestWidth)
{
greatestWidth = line.GetWidthWithoutTrailingSpaces();
}
foreach (var lineFragment in line.LineFragments)
{
var displayText = lineFragment.Text;
if (p.TextRuns.Count == 0 && string.IsNullOrEmpty(textIfEmpty) == false)
{
AddText(displayText, p.DefaultRunProperties, prevWidth);
}
else
{
var idx = _newTextFragments.IndexOf(lineFragment.OriginalTextFragment);
AddRenderItemTextRun(p.TextRuns[idx], displayText, prevWidth);
}
TextRunItem runItem = Runs.Last();
runItem.YPosition = runLineSpacing;
runItem.Bounds.Width = lineFragment.Width;
prevWidth += lineFragment.Width;
}
lastDescent = line.LargestDescent;
}
}
Bounds.Height = runLineSpacing + lastDescent;
Bounds.Width = greatestWidth;
Bounds.Width = greatestWidth;
}
List<TextLineSimple> WrapToSimpleTextLines(ExcelDrawingParagraph p)
{
if (_newTextFragments.Count > 0)
{
if(_layout == null)
{
_layout = OpenTypeFonts.GetTextLayoutEngineForFont((_newTextFragments[0].Font));
}
var maxWidthPoints = Math.Round(ParentTextBody.MaxWidth, 0, MidpointRounding.AwayFromZero);
return _layout.WrapRichTextLines(_newTextFragments, maxWidthPoints);
}
return new List<TextLineSimple>();
}
internal double GetAlignmentHorizontal(eTextAlignment txAlignment)
{
var area = Bounds;
double x = 0;
switch (txAlignment)
{
case eTextAlignment.Left:
default:
x = area.Left + _leftMargin;
break;
case eTextAlignment.Center:
x = (area.Right / 2) + _leftMargin - _rightMargin;
break;
case eTextAlignment.Right:
x = area.Right - _rightMargin;
break;
}
return x;
}
/// <summary>
/// Type of textrun defined by child type
/// </summary>
/// <param name="run"></param>
/// <param name="parent"></param>
/// <param name="DisplayString"></param>
/// <returns></returns>
internal abstract TextRunItem CreateTextRun(ExcelParagraphTextRunBase run, BoundingBox parent, string displayText);
internal abstract TextRunItem CreateTextRun(string text, ExcelTextFont font, BoundingBox parent, string displayText);
internal abstract TextRunItem CreateTextRun(MeasurementFont font, BoundingBox parent, string displayText);
}
}