Compare commits

...

2 Commits

Author SHA1 Message Date
MarcinZiabek 662a55e21c Implemented text shaping prototype 2022-03-01 23:22:14 +01:00
MarcinZiabek 7d825d123b Created text measuring algorithm for shaped text via HarfBuzz 2022-02-28 23:31:51 +01:00
22 changed files with 392 additions and 245 deletions
+2 -2
View File
@@ -236,7 +236,7 @@ namespace QuestPDF.Examples
.Padding(10) .Padding(10)
.Text(text => .Text(text =>
{ {
text.DefaultTextStyle(TextStyle.Default); text.DefaultTextStyle(TextStyle.Default.BackgroundColor(Colors.Grey.Lighten3));
text.AlignLeft(); text.AlignLeft();
text.ParagraphSpacing(10); text.ParagraphSpacing(10);
@@ -251,7 +251,7 @@ namespace QuestPDF.Examples
text.EmptyLine(); text.EmptyLine();
foreach (var i in Enumerable.Range(1, 100)) foreach (var i in Enumerable.Range(1, 1000))
{ {
text.Line($"{i}: {Placeholders.Paragraph()}"); text.Line($"{i}: {Placeholders.Paragraph()}");
+161
View File
@@ -0,0 +1,161 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
using NUnit.Framework;
using QuestPDF.Drawing;
using QuestPDF.Examples.Engine;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SkiaSharp;
using SkiaSharp.HarfBuzz;
namespace QuestPDF.Examples
{
public class TextShapingTests
{
[Test]
public void ShapeText()
{
using var textPaint = new SKPaint
{
Color = SKColors.Black,
Typeface = SKTypeface.CreateDefault(),
IsAntialias = true,
TextSize = 20
};
using var backgroundPaint = new SKPaint
{
Color = SKColors.LightGray
};
RenderingTest
.Create()
.PageSize(550, 250)
.ProduceImages()
.ShowResults()
.Render(container =>
{
//var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec odio ipsum, aliquam a neque a, lacinia vehicula lectus.";
//var arabic = "ينا الألم. في بعض الأحيان ونظراً للالتزامات التي يفرضها علينا الواجب والعمل سنتنازل غالباً ونرفض الشعور";
var lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
var arabic = "ينا الألم. في بعض الأحيان ونظراً للالتزامات التي يفرضها علينا";
var text = arabic;
var metrics = textPaint.FontMetrics;
container
.Padding(25)
.Canvas((canvas, space) =>
{
canvas.Translate(0, 20);
var width = MeasureText(text, textPaint);
var widthReal = textPaint.MeasureText(text);
canvas.DrawRect(0, metrics.Descent, width, metrics.Ascent - metrics.Descent, backgroundPaint);
canvas.DrawShapedText(text, 0, 0, textPaint);
canvas.Translate(0, 40);
canvas.DrawText(text, 0, 0, textPaint);
});
});
}
float MeasureText(string text, SKPaint paint)
{
var font = paint.ToFont();
using var shaper = new SKShaper(paint.Typeface);
var result = shaper.Shape(text + " ", paint);
return Math.Max(result.Points.First().X, result.Points.Last().X);
var glyphCount = result.Codepoints.Length;
var glyphIds = new ushort[glyphCount];
var glyphWidths = new float[glyphCount];
var glyphBounds = new SKRect[glyphCount];
font.GetGlyphs(result.Codepoints.Select(x => (int)x).ToArray(), glyphIds);
font.GetGlyphWidths(glyphIds, glyphWidths, glyphBounds);
return glyphWidths.Sum();
return result.Points.Max(p => p.X);
using var skTextBlobBuilder = new SKTextBlobBuilder();
var positionedRunBuffer = skTextBlobBuilder.AllocatePositionedRun(font, result.Codepoints.Length);
var glyphSpan = positionedRunBuffer.GetGlyphSpan();
var positionSpan = positionedRunBuffer.GetPositionSpan();
for (int index = 0; index < result.Codepoints.Length; ++index)
{
glyphSpan[index] = (ushort) result.Codepoints[index];
positionSpan[index] = result.Points[index];
}
using var text1 = skTextBlobBuilder.Build();
return text1.Bounds.Width;
}
[Test]
public void ShapeSingle()
{
using var textPaint = new SKPaint
{
Color = SKColors.Black,
Typeface = SKTypeface.CreateDefault(),
IsAntialias = true,
TextSize = 20
};
var text = string.Join(" ", Enumerable.Range(0, 10_000).Select(x => Placeholders.Sentence()));
using var shaper = new SKShaper(textPaint.Typeface);
var result = shaper.Shape(text + " ", textPaint);
}
[Test]
public void ShapeMany()
{
using var textPaint = new SKPaint
{
Color = SKColors.Black,
Typeface = SKTypeface.CreateDefault(),
IsAntialias = true,
TextSize = 20
};
var text = string.Join(" ", Enumerable.Range(0, 1_000).Select(x => Placeholders.Sentence()));
foreach (var part in Regex.Split(text, "( )|(\\w+)"))
{
using var shaper = new SKShaper(textPaint.Typeface);
var result = shaper.Shape(part + " ", textPaint);
}
}
[Test]
public void ShapeMany2()
{
using var textPaint = new SKPaint
{
Color = SKColors.Black,
Typeface = SKTypeface.CreateDefault(),
IsAntialias = true,
TextSize = 20
};
using var shaper = new SKShaper(textPaint.Typeface);
foreach (var i in Enumerable.Range(0, 10_000))
{
var text = Placeholders.Paragraph();
textPaint.MeasureText(text);
var result = shaper.Shape(text + " ", textPaint);
}
}
}
}
@@ -19,6 +19,7 @@ namespace QuestPDF.UnitTests.TestEngine
public void DrawRectangle(Position vector, Size size, string color) => DrawRectFunc(vector, size, color); public void DrawRectangle(Position vector, Size size, string color) => DrawRectFunc(vector, size, color);
public void DrawText(string text, Position position, TextStyle style) => DrawTextFunc(text, position, style); public void DrawText(string text, Position position, TextStyle style) => DrawTextFunc(text, position, style);
public void DrawShapedText(string text, Position position, TextStyle style) => DrawTextFunc(text, position, style);
public void DrawImage(SKImage image, Position position, Size size) => DrawImageFunc(image, position, size); public void DrawImage(SKImage image, Position position, Size size) => DrawImageFunc(image, position, size);
public void DrawHyperlink(string url, Size size) => throw new NotImplementedException(); public void DrawHyperlink(string url, Size size) => throw new NotImplementedException();
@@ -16,6 +16,7 @@ namespace QuestPDF.UnitTests.TestEngine
public void DrawRectangle(Position vector, Size size, string color) => Operations.Add(new CanvasDrawRectangleOperation(vector, size, color)); public void DrawRectangle(Position vector, Size size, string color) => Operations.Add(new CanvasDrawRectangleOperation(vector, size, color));
public void DrawText(string text, Position position, TextStyle style) => Operations.Add(new CanvasDrawTextOperation(text, position, style)); public void DrawText(string text, Position position, TextStyle style) => Operations.Add(new CanvasDrawTextOperation(text, position, style));
public void DrawShapedText(string text, Position position, TextStyle style) => Operations.Add(new CanvasDrawTextOperation(text, position, style));
public void DrawImage(SKImage image, Position position, Size size) => Operations.Add(new CanvasDrawImageOperation(position, size)); public void DrawImage(SKImage image, Position position, Size size) => Operations.Add(new CanvasDrawImageOperation(position, size));
public void DrawHyperlink(string url, Size size) => throw new NotImplementedException(); public void DrawHyperlink(string url, Size size) => throw new NotImplementedException();
+13
View File
@@ -4,6 +4,7 @@ using System.IO;
using System.Linq; using System.Linq;
using QuestPDF.Infrastructure; using QuestPDF.Infrastructure;
using SkiaSharp; using SkiaSharp;
using SkiaSharp.HarfBuzz;
namespace QuestPDF.Drawing namespace QuestPDF.Drawing
{ {
@@ -12,6 +13,8 @@ namespace QuestPDF.Drawing
private static ConcurrentDictionary<string, FontStyleSet> StyleSets = new(); private static ConcurrentDictionary<string, FontStyleSet> StyleSets = new();
private static ConcurrentDictionary<object, SKFontMetrics> FontMetrics = new(); private static ConcurrentDictionary<object, SKFontMetrics> FontMetrics = new();
private static ConcurrentDictionary<object, SKPaint> Paints = new(); private static ConcurrentDictionary<object, SKPaint> Paints = new();
private static ConcurrentDictionary<object, SKFont> Fonts = new();
private static ConcurrentDictionary<object, SKShaper> Shapers = new();
private static ConcurrentDictionary<string, SKPaint> ColorPaint = new(); private static ConcurrentDictionary<string, SKPaint> ColorPaint = new();
private static void RegisterFontType(SKData fontData, string? customName = null) private static void RegisterFontType(SKData fontData, string? customName = null)
@@ -94,9 +97,19 @@ namespace QuestPDF.Drawing
} }
} }
internal static SKFont ToFont(this TextStyle style)
{
return Fonts.GetOrAdd(style.FontMetricsKey, _ => style.ToPaint().Typeface.ToFont());
}
internal static SKFontMetrics ToFontMetrics(this TextStyle style) internal static SKFontMetrics ToFontMetrics(this TextStyle style)
{ {
return FontMetrics.GetOrAdd(style.FontMetricsKey, key => style.ToPaint().FontMetrics); return FontMetrics.GetOrAdd(style.FontMetricsKey, key => style.ToPaint().FontMetrics);
} }
internal static SKShaper ToShaper(this TextStyle style)
{
return Shapers.GetOrAdd(style.FontMetricsKey, _ => new SKShaper(style.ToFont().Typeface));
}
} }
} }
+5
View File
@@ -46,6 +46,11 @@ namespace QuestPDF.Drawing
} }
public void DrawShapedText(string text, Position position, TextStyle style)
{
}
public void DrawImage(SKImage image, Position position, Size size) public void DrawImage(SKImage image, Position position, Size size)
{ {
+6
View File
@@ -1,5 +1,6 @@
using QuestPDF.Infrastructure; using QuestPDF.Infrastructure;
using SkiaSharp; using SkiaSharp;
using SkiaSharp.HarfBuzz;
namespace QuestPDF.Drawing namespace QuestPDF.Drawing
{ {
@@ -32,6 +33,11 @@ namespace QuestPDF.Drawing
Canvas.DrawText(text, vector.X, vector.Y, style.ToPaint()); Canvas.DrawText(text, vector.X, vector.Y, style.ToPaint());
} }
public void DrawShapedText(string text, Position vector, TextStyle style)
{
Canvas.DrawShapedText(text, vector.X, vector.Y, style.ToPaint());
}
public void DrawImage(SKImage image, Position vector, Size size) public void DrawImage(SKImage image, Position vector, Size size)
{ {
Canvas.DrawImage(image, new SKRect(vector.X, vector.Y, size.Width, size.Height)); Canvas.DrawImage(image, new SKRect(vector.X, vector.Y, size.Width, size.Height));
@@ -2,7 +2,7 @@
namespace QuestPDF.Elements.Text.Calculation namespace QuestPDF.Elements.Text.Calculation
{ {
internal class TextMeasurementResult internal class TextBlockSize
{ {
public float Width { get; set; } public float Width { get; set; }
public float Height => Math.Abs(Descent) + Math.Abs(Ascent); public float Height => Math.Abs(Descent) + Math.Abs(Ascent);
@@ -11,12 +11,5 @@ namespace QuestPDF.Elements.Text.Calculation
public float Descent { get; set; } public float Descent { get; set; }
public float LineHeight { get; set; } public float LineHeight { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public int NextIndex { get; set; }
public int TotalIndex { get; set; }
public bool IsLast => EndIndex == TotalIndex;
} }
} }
@@ -2,14 +2,8 @@
namespace QuestPDF.Elements.Text.Calculation namespace QuestPDF.Elements.Text.Calculation
{ {
internal class TextDrawingRequest internal struct TextDrawingRequest
{ {
public ICanvas Canvas { get; set; }
public IPageContext PageContext { get; set; }
public int StartIndex { get; set; }
public int EndIndex { get; set; }
public float TotalAscent { get; set; } public float TotalAscent { get; set; }
public Size TextSize { get; set; } public Size TextSize { get; set; }
} }
@@ -5,6 +5,6 @@ namespace QuestPDF.Elements.Text.Calculation
internal class TextLineElement internal class TextLineElement
{ {
public ITextBlockItem Item { get; set; } public ITextBlockItem Item { get; set; }
public TextMeasurementResult Measurement { get; set; } public TextBlockSize Measurement { get; set; }
} }
} }
@@ -1,14 +0,0 @@
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements.Text.Calculation
{
internal class TextMeasurementRequest
{
public ICanvas Canvas { get; set; }
public IPageContext PageContext { get; set; }
public int StartIndex { get; set; }
public float AvailableWidth { get; set; }
public bool IsFirstLineElement { get; set; }
}
}
@@ -5,7 +5,10 @@ namespace QuestPDF.Elements.Text.Items
{ {
internal interface ITextBlockItem internal interface ITextBlockItem
{ {
TextMeasurementResult? Measure(TextMeasurementRequest request); ICanvas Canvas { get; set; }
IPageContext PageContext { get; set; }
TextBlockSize? Measure();
void Draw(TextDrawingRequest request); void Draw(TextDrawingRequest request);
} }
} }
@@ -7,41 +7,40 @@ namespace QuestPDF.Elements.Text.Items
{ {
internal class TextBlockElement : ITextBlockItem internal class TextBlockElement : ITextBlockItem
{ {
public ICanvas Canvas { get; set; }
public IPageContext PageContext { get; set; }
public Element Element { get; set; } = Empty.Instance; public Element Element { get; set; } = Empty.Instance;
public TextMeasurementResult? Measure(TextMeasurementRequest request) public TextBlockSize? Measure()
{ {
Element.VisitChildren(x => (x as IStateResettable)?.ResetState()); Element.VisitChildren(x => (x as IStateResettable)?.ResetState());
Element.VisitChildren(x => x.Initialize(request.PageContext, request.Canvas)); Element.VisitChildren(x => x.Initialize(PageContext, Canvas));
var measurement = Element.Measure(new Size(request.AvailableWidth, Size.Max.Height)); var measurement = Element.Measure(Size.Max);
if (measurement.Type != SpacePlanType.FullRender) if (measurement.Type != SpacePlanType.FullRender)
return null; return null;
return new TextMeasurementResult return new TextBlockSize
{ {
Width = measurement.Width, Width = measurement.Width,
Ascent = -measurement.Height, Ascent = -measurement.Height,
Descent = 0, Descent = 0,
LineHeight = 1, LineHeight = 1
StartIndex = 0,
EndIndex = 0,
TotalIndex = 0
}; };
} }
public void Draw(TextDrawingRequest request) public void Draw(TextDrawingRequest request)
{ {
Element.VisitChildren(x => (x as IStateResettable)?.ResetState()); Element.VisitChildren(x => (x as IStateResettable)?.ResetState());
Element.VisitChildren(x => x.Initialize(request.PageContext, request.Canvas)); Element.VisitChildren(x => x.Initialize(PageContext, Canvas));
request.Canvas.Translate(new Position(0, request.TotalAscent)); Canvas.Translate(new Position(0, request.TotalAscent));
Element.Draw(new Size(request.TextSize.Width, -request.TotalAscent)); Element.Draw(new Size(request.TextSize.Width, -request.TotalAscent));
request.Canvas.Translate(new Position(0, -request.TotalAscent)); Canvas.Translate(new Position(0, -request.TotalAscent));
} }
} }
} }
@@ -7,16 +7,11 @@ namespace QuestPDF.Elements.Text.Items
{ {
public string Url { get; set; } public string Url { get; set; }
public override TextMeasurementResult? Measure(TextMeasurementRequest request)
{
return MeasureWithoutCache(request);
}
public override void Draw(TextDrawingRequest request) public override void Draw(TextDrawingRequest request)
{ {
request.Canvas.Translate(new Position(0, request.TotalAscent)); Canvas.Translate(new Position(0, request.TotalAscent));
request.Canvas.DrawHyperlink(Url, new Size(request.TextSize.Width, request.TextSize.Height)); Canvas.DrawHyperlink(Url, new Size(request.TextSize.Width, request.TextSize.Height));
request.Canvas.Translate(new Position(0, -request.TotalAscent)); Canvas.Translate(new Position(0, -request.TotalAscent));
base.Draw(request); base.Draw(request);
} }
@@ -9,21 +9,21 @@ namespace QuestPDF.Elements.Text.Items
public const string PageNumberPlaceholder = "123"; public const string PageNumberPlaceholder = "123";
public Func<IPageContext, string> Source { get; set; } = _ => PageNumberPlaceholder; public Func<IPageContext, string> Source { get; set; } = _ => PageNumberPlaceholder;
public override TextMeasurementResult? Measure(TextMeasurementRequest request) public override TextBlockSize? Measure()
{ {
SetPageNumber(request.PageContext); SetPageNumber();
return MeasureWithoutCache(request); return base.Measure();
} }
public override void Draw(TextDrawingRequest request) public override void Draw(TextDrawingRequest request)
{ {
SetPageNumber(request.PageContext); SetPageNumber();
base.Draw(request); base.Draw(request);
} }
private void SetPageNumber(IPageContext context) private void SetPageNumber()
{ {
Text = Source(context) ?? PageNumberPlaceholder; Text = Source(PageContext) ?? PageNumberPlaceholder;
} }
} }
} }
@@ -0,0 +1,19 @@
using QuestPDF.Elements.Text.Calculation;
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements.Text.Items
{
internal class TextBlockSectionLink : TextBlockSpan
{
public string SectionName { get; set; }
public override void Draw(TextDrawingRequest request)
{
Canvas.Translate(new Position(0, request.TotalAscent));
Canvas.DrawSectionLink(SectionName, new Size(request.TextSize.Width, request.TextSize.Height));
Canvas.Translate(new Position(0, -request.TotalAscent));
base.Draw(request);
}
}
}
@@ -1,24 +0,0 @@
using QuestPDF.Elements.Text.Calculation;
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements.Text.Items
{
internal class TextBlockSectionlLink : TextBlockSpan
{
public string SectionName { get; set; }
public override TextMeasurementResult? Measure(TextMeasurementRequest request)
{
return MeasureWithoutCache(request);
}
public override void Draw(TextDrawingRequest request)
{
request.Canvas.Translate(new Position(0, request.TotalAscent));
request.Canvas.DrawSectionLink(SectionName, new Size(request.TextSize.Width, request.TextSize.Height));
request.Canvas.Translate(new Position(0, -request.TotalAscent));
base.Draw(request);
}
}
}
+48 -78
View File
@@ -1,107 +1,72 @@
using System.Collections.Generic; using System;
using System.Collections.Generic;
using System.Linq;
using QuestPDF.Drawing; using QuestPDF.Drawing;
using QuestPDF.Elements.Text.Calculation; using QuestPDF.Elements.Text.Calculation;
using QuestPDF.Infrastructure; using QuestPDF.Infrastructure;
using SkiaSharp.HarfBuzz;
using Size = QuestPDF.Infrastructure.Size; using Size = QuestPDF.Infrastructure.Size;
namespace QuestPDF.Elements.Text.Items namespace QuestPDF.Elements.Text.Items
{ {
internal class TextBlockSpan : ITextBlockItem internal class TextBlockSpan : ITextBlockItem
{ {
public ICanvas Canvas { get; set; }
public IPageContext PageContext { get; set; }
public string Text { get; set; } public string Text { get; set; }
public TextStyle Style { get; set; } = new TextStyle(); public TextStyle Style { get; set; }
private Dictionary<(int startIndex, float availableWidth), TextMeasurementResult?> MeasureCache = protected TextBlockSize? Size { get; set; }
new Dictionary<(int startIndex, float availableWidth), TextMeasurementResult?>(); protected bool RequiresShaping { get; set; }
public virtual TextMeasurementResult? Measure(TextMeasurementRequest request) public virtual TextBlockSize? Measure()
{ {
var cacheKey = (request.StartIndex, request.AvailableWidth); Size ??= Text == " " ? GetSizeForSpace() : GetSizeForWord();
return Size;
if (!MeasureCache.ContainsKey(cacheKey))
MeasureCache[cacheKey] = MeasureWithoutCache(request);
return MeasureCache[cacheKey];
} }
internal TextMeasurementResult? MeasureWithoutCache(TextMeasurementRequest request) private TextBlockSize GetSizeForWord()
{ {
const char space = ' ';
var paint = Style.ToPaint(); var paint = Style.ToPaint();
var fontMetrics = Style.ToFontMetrics(); var fontMetrics = Style.ToFontMetrics();
var startIndex = request.StartIndex; var shaper = Style.ToShaper();
if (request.IsFirstLineElement) // shaper returns positions of all glyphs,
{ // by adding a space, it is possible to capture width of the last original character
while (startIndex + 1 < Text.Length && Text[startIndex] == space) var result = shaper.Shape(Text + " ", paint);
startIndex++;
}
if (Text.Length == 0) // when text is left-to-right: last value corresponds to text width
{ // when text is right-to-left: glyphs are in the reverse order, first value represents text width
return new TextMeasurementResult var width = Math.Max(result.Points.First().X, result.Points.Last().X);
{
Width = 0,
LineHeight = Style.LineHeight ?? 1, RequiresShaping = result.Points.Length != Text.Length + 1;
Ascent = fontMetrics.Ascent,
Descent = fontMetrics.Descent
};
}
// start breaking text from requested position return new TextBlockSize
var text = Text.Substring(startIndex);
var textLength = (int)paint.BreakText(text, request.AvailableWidth);
if (textLength <= 0)
return null;
if (textLength < text.Length && text[textLength] == space)
textLength++;
// break text only on spaces
if (textLength < text.Length)
{
var lastSpaceIndex = text.Substring(0, textLength).LastIndexOf(space) - 1;
if (lastSpaceIndex <= 0)
{
if (!request.IsFirstLineElement)
return null;
}
else
{
textLength = lastSpaceIndex + 1;
}
}
text = text.Substring(0, textLength);
var endIndex = startIndex + textLength;
var nextIndex = endIndex;
while (nextIndex + 1 < Text.Length && Text[nextIndex] == space)
nextIndex++;
// measure final text
var width = paint.MeasureText(text);
return new TextMeasurementResult
{ {
Width = width, Width = width,
Ascent = fontMetrics.Ascent, Ascent = fontMetrics.Ascent,
Descent = fontMetrics.Descent, Descent = fontMetrics.Descent,
LineHeight = Style.LineHeight ?? 1, LineHeight = Style.LineHeight ?? 1
};
}
StartIndex = startIndex, private TextBlockSize GetSizeForSpace()
EndIndex = endIndex, {
NextIndex = nextIndex, var paint = Style.ToPaint();
TotalIndex = Text.Length var fontMetrics = Style.ToFontMetrics();
return new TextBlockSize
{
Width = paint.MeasureText(" "),
Ascent = fontMetrics.Ascent,
Descent = fontMetrics.Descent,
LineHeight = Style.LineHeight ?? 1
}; };
} }
@@ -109,10 +74,15 @@ namespace QuestPDF.Elements.Text.Items
{ {
var fontMetrics = Style.ToFontMetrics(); var fontMetrics = Style.ToFontMetrics();
var text = Text.Substring(request.StartIndex, request.EndIndex - request.StartIndex); Canvas.DrawRectangle(new Position(0, request.TotalAscent), new Size(request.TextSize.Width, request.TextSize.Height), Style.BackgroundColor);
request.Canvas.DrawRectangle(new Position(0, request.TotalAscent), new Size(request.TextSize.Width, request.TextSize.Height), Style.BackgroundColor); if (!string.IsNullOrWhiteSpace(Text))
request.Canvas.DrawText(text, Position.Zero, Style); {
if (RequiresShaping)
Canvas.DrawShapedText(Text, Position.Zero, Style);
else
Canvas.DrawText(Text, Position.Zero, Style);
}
// draw underline // draw underline
if ((Style.HasUnderline ?? false) && fontMetrics.UnderlinePosition.HasValue) if ((Style.HasUnderline ?? false) && fontMetrics.UnderlinePosition.HasValue)
@@ -124,7 +94,7 @@ namespace QuestPDF.Elements.Text.Items
void DrawLine(float offset, float thickness) void DrawLine(float offset, float thickness)
{ {
request.Canvas.DrawRectangle(new Position(0, offset - thickness / 2f), new Size(request.TextSize.Width, thickness), Style.Color); Canvas.DrawRectangle(new Position(0, offset - thickness / 2f), new Size(request.TextSize.Width, thickness), Style.Color);
} }
} }
} }
+78 -55
View File
@@ -1,6 +1,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions;
using QuestPDF.Drawing; using QuestPDF.Drawing;
using QuestPDF.Elements.Text.Calculation; using QuestPDF.Elements.Text.Calculation;
using QuestPDF.Elements.Text.Items; using QuestPDF.Elements.Text.Items;
@@ -11,22 +12,53 @@ namespace QuestPDF.Elements.Text
internal class TextBlock : Element, IStateResettable internal class TextBlock : Element, IStateResettable
{ {
public HorizontalAlignment Alignment { get; set; } = HorizontalAlignment.Left; public HorizontalAlignment Alignment { get; set; } = HorizontalAlignment.Left;
public List<ITextBlockItem> Items { get; set; } = new List<ITextBlockItem>(); public List<ITextBlockItem> Items { get; set; } = new();
public string Text => string.Join(" ", Items.Where(x => x is TextBlockSpan).Cast<TextBlockSpan>().Select(x => x.Text)); public string Text => string.Join(" ", Items.Where(x => x is TextBlockSpan).Cast<TextBlockSpan>().Select(x => x.Text));
private Queue<ITextBlockItem> RenderingQueue { get; set; }
private int CurrentElementIndex { get; set; } private int CurrentElementIndex { get; set; }
internal override void Initialize(IPageContext pageContext, ICanvas canvas)
{
Items = SplitElementsBySpace().ToList();
Items.ForEach(x =>
{
x.PageContext = pageContext;
x.Canvas = canvas;
});
base.Initialize(pageContext, canvas);
}
public void ResetState() public void ResetState()
{ {
RenderingQueue = new Queue<ITextBlockItem>(Items);
CurrentElementIndex = 0; CurrentElementIndex = 0;
} }
private IEnumerable<ITextBlockItem> SplitElementsBySpace()
{
foreach (var item in Items)
{
if (item is TextBlockSpan span)
{
span.Text ??= "";
foreach (var spanItem in Regex.Split(span.Text, "( )|([^ ]+)"))
{
yield return new TextBlockSpan
{
Text = spanItem,
Style = span.Style
};
}
}
}
}
internal override SpacePlan Measure(Size availableSpace) internal override SpacePlan Measure(Size availableSpace)
{ {
if (!RenderingQueue.Any()) if (!Items.Any())
return SpacePlan.FullRender(Size.Zero); return SpacePlan.FullRender(Size.Zero);
var lines = DivideTextItemsIntoLines(availableSpace.Width, availableSpace.Height).ToList(); var lines = DivideTextItemsIntoLines(availableSpace.Width, availableSpace.Height).ToList();
@@ -40,12 +72,7 @@ namespace QuestPDF.Elements.Text
if (width > availableSpace.Width + Size.Epsilon || height > availableSpace.Height + Size.Epsilon) if (width > availableSpace.Width + Size.Epsilon || height > availableSpace.Height + Size.Epsilon)
return SpacePlan.Wrap(); return SpacePlan.Wrap();
var fullyRenderedItemsCount = lines if (CurrentElementIndex + lines.Sum(x => x.Elements.Count) == Items.Count)
.SelectMany(x => x.Elements)
.GroupBy(x => x.Item)
.Count(x => x.Any(y => y.Measurement.IsLast));
if (fullyRenderedItemsCount == RenderingQueue.Count)
return SpacePlan.FullRender(width, height); return SpacePlan.FullRender(width, height);
return SpacePlan.PartialRender(width, height); return SpacePlan.PartialRender(width, height);
@@ -61,10 +88,37 @@ namespace QuestPDF.Elements.Text
var heightOffset = 0f; var heightOffset = 0f;
var widthOffset = 0f; var widthOffset = 0f;
foreach (var line in lines) var isLastPart = lines.Sum(x => x.Elements.Count) + CurrentElementIndex == Items.Count;
foreach (var sourceLine in lines)
{ {
widthOffset = 0f; widthOffset = 0f;
var isLastLine = sourceLine == lines.Last();
var line = sourceLine;
if (!(isLastPart && isLastLine))
{
var spans = sourceLine.Elements
.Where(x => x.Item is TextBlockSpan)
.SkipWhile(x => string.IsNullOrWhiteSpace((x.Item as TextBlockSpan).Text))
.Reverse()
.SkipWhile(x => string.IsNullOrWhiteSpace((x.Item as TextBlockSpan).Text))
.Reverse()
.ToList();
var wordsWidth = spans
.Where(x => !string.IsNullOrWhiteSpace((x.Item as TextBlockSpan).Text))
.Sum(x => x.Measurement.Width);
var spaceSpans = spans.Where(x => string.IsNullOrWhiteSpace((x.Item as TextBlockSpan).Text)).ToList();
var spaceWidth = (availableSpace.Width - wordsWidth) / spaceSpans.Count;
spaceSpans.ForEach(x => x.Measurement.Width = spaceWidth);
line = TextLine.From(spans);
}
var alignmentOffset = GetAlignmentOffset(line.Width); var alignmentOffset = GetAlignmentOffset(line.Width);
Canvas.Translate(new Position(alignmentOffset, 0)); Canvas.Translate(new Position(alignmentOffset, 0));
@@ -74,12 +128,6 @@ namespace QuestPDF.Elements.Text
{ {
var textDrawingRequest = new TextDrawingRequest var textDrawingRequest = new TextDrawingRequest
{ {
Canvas = Canvas,
PageContext = PageContext,
StartIndex = item.Measurement.StartIndex,
EndIndex = item.Measurement.EndIndex,
TextSize = new Size(item.Measurement.Width, line.LineHeight), TextSize = new Size(item.Measurement.Width, line.LineHeight),
TotalAscent = line.Ascent TotalAscent = line.Ascent
}; };
@@ -98,19 +146,9 @@ namespace QuestPDF.Elements.Text
} }
Canvas.Translate(new Position(0, -heightOffset)); Canvas.Translate(new Position(0, -heightOffset));
CurrentElementIndex += lines.Sum(x => x.Elements.Count);
lines if (CurrentElementIndex == Items.Count)
.SelectMany(x => x.Elements)
.GroupBy(x => x.Item)
.Where(x => x.Any(y => y.Measurement.IsLast))
.Select(x => x.Key)
.ToList()
.ForEach(x => RenderingQueue.Dequeue());
var lastElementMeasurement = lines.Last().Elements.Last().Measurement;
CurrentElementIndex = lastElementMeasurement.IsLast ? 0 : lastElementMeasurement.NextIndex;
if (!RenderingQueue.Any())
ResetState(); ResetState();
float GetAlignmentOffset(float lineWidth) float GetAlignmentOffset(float lineWidth)
@@ -130,13 +168,12 @@ namespace QuestPDF.Elements.Text
} }
} }
public IEnumerable<TextLine> DivideTextItemsIntoLines(float availableWidth, float availableHeight) private IEnumerable<TextLine> DivideTextItemsIntoLines(float availableWidth, float availableHeight)
{ {
var queue = new Queue<ITextBlockItem>(RenderingQueue);
var currentItemIndex = CurrentElementIndex; var currentItemIndex = CurrentElementIndex;
var currentHeight = 0f; var currentHeight = 0f;
while (queue.Any()) while (true)
{ {
var line = GetNextLine(); var line = GetNextLine();
@@ -158,40 +195,26 @@ namespace QuestPDF.Elements.Text
while (true) while (true)
{ {
if (!queue.Any()) if (currentItemIndex == Items.Count)
break; break;
var currentElement = queue.Peek(); var currentElement = Items[currentItemIndex];
var textBlockSize = currentElement.Measure();
var measurementRequest = new TextMeasurementRequest if (textBlockSize == null)
{ break;
Canvas = Canvas,
PageContext = PageContext,
StartIndex = currentItemIndex, if (currentWidth + textBlockSize.Width > availableWidth + Size.Epsilon)
AvailableWidth = availableWidth - currentWidth,
IsFirstLineElement = !currentLineElements.Any()
};
var measurementResponse = currentElement.Measure(measurementRequest);
if (measurementResponse == null)
break; break;
currentLineElements.Add(new TextLineElement currentLineElements.Add(new TextLineElement
{ {
Item = currentElement, Item = currentElement,
Measurement = measurementResponse Measurement = textBlockSize
}); });
currentWidth += measurementResponse.Width; currentWidth += textBlockSize.Width;
currentItemIndex = measurementResponse.NextIndex; currentItemIndex ++;
if (!measurementResponse.IsLast)
break;
currentItemIndex = 0;
queue.Dequeue();
} }
return TextLine.From(currentLineElements); return TextLine.From(currentLineElements);
+1 -1
View File
@@ -150,7 +150,7 @@ namespace QuestPDF.Fluent
style ??= TextStyle.Default; style ??= TextStyle.Default;
AddItemToLastTextBlock(new TextBlockSectionlLink AddItemToLastTextBlock(new TextBlockSectionLink
{ {
Style = style, Style = style,
Text = text, Text = text,
+1
View File
@@ -8,6 +8,7 @@ namespace QuestPDF.Infrastructure
void DrawRectangle(Position vector, Size size, string color); void DrawRectangle(Position vector, Size size, string color);
void DrawText(string text, Position position, TextStyle style); void DrawText(string text, Position position, TextStyle style);
void DrawShapedText(string text, Position position, TextStyle style);
void DrawImage(SKImage image, Position position, Size size); void DrawImage(SKImage image, Position position, Size size);
void DrawHyperlink(string url, Size size); void DrawHyperlink(string url, Size size);
+1
View File
@@ -25,6 +25,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="SkiaSharp" Version="2.80.3" /> <PackageReference Include="SkiaSharp" Version="2.80.3" />
<PackageReference Include="SkiaSharp.HarfBuzz" Version="2.80.3" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>