Compare commits

..

2 Commits

Author SHA1 Message Date
MarcinZiabek bd577b9609 Implemented custom tree view with proper indendation 2022-07-18 10:47:07 +02:00
MarcinZiabek 100afbdc32 Prototype implementation 2022-07-12 15:21:50 +02:00
99 changed files with 1395 additions and 2476 deletions
@@ -1,411 +0,0 @@
using System;
using System.Linq;
using NUnit.Framework;
using QuestPDF.Drawing.Exceptions;
using QuestPDF.Elements;
using QuestPDF.Examples.Engine;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
namespace QuestPDF.Examples
{
public class ContentDirectionExamples
{
private Action<IContainer> ContentDirectionTemplate(Action<IContainer> content)
{
return container =>
{
container
.Padding(20)
.MinimalBox()
.Border(1)
.ExtendHorizontal()
.Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.RelativeColumn();
});
table.Header(header =>
{
header.Cell().ContentFromLeftToRight().Element(HeaderCell("Left-to-right"));
header.Cell().ContentFromRightToLeft().Element(HeaderCell("Right-to-left"));
static Action<IContainer> HeaderCell(string label)
{
return container => container
.Border(1)
.BorderColor(Colors.Grey.Medium)
.Background(Colors.Grey.Lighten3)
.PaddingHorizontal(10)
.PaddingVertical(5)
.Text(label)
.FontSize(18)
.SemiBold();
}
});
table.Cell().Element(TestCell).ContentFromLeftToRight().Element(content);
table.Cell()
.Element(TestCell)
.ContentFromRightToLeft()
.Element(content);
static IContainer TestCell(IContainer container)
{
return container.Border(1).BorderColor(Colors.Grey.Medium).Padding(10);
}
});
};
}
[Test]
public void Page()
{
RenderingTest
.Create()
.ProduceImages()
.ShowResults()
.EnableDebugging()
.RenderDocument(document =>
{
document.Page(page =>
{
page.Size(PageSizes.A5);
page.Margin(20);
page.PageColor(Colors.White);
//page.ContentFromRightToLeft();
page.Content().Column(column =>
{
column.Spacing(20);
column.Item().Row(row =>
{
row.Spacing(10);
row.AutoItem().AlignMiddle().Width(20).Height(20).Image(Placeholders.Image);
row.RelativeItem()
.Text("Document title")
.FontSize(24).FontColor(Colors.Blue.Accent1).SemiBold();
});
column.Item().Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.RelativeColumn();
columns.RelativeColumn();
columns.RelativeColumn();
});
foreach (var i in Enumerable.Range(0, 9))
{
var width = (i % 4 == 0) ? 2 : 1;
table
.Cell()
.ColumnSpan((uint)width)
.Background(i % 4 == 0 ? Colors.Grey.Lighten1 : Colors.Grey.Lighten2)
.Padding(5)
.AlignCenter()
.Text(i)
.FontSize(20);
}
});
});
});
});
}
[Test]
public void Column()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Column(column =>
{
column.Spacing(5);
column.Item().Height(50).Width(50).Background(Colors.Red.Lighten1);
column.Item().Height(50).Width(100).Background(Colors.Green.Lighten1);
column.Item().Height(50).Width(150).Background(Colors.Blue.Lighten1);
});
}
}
[Test]
public void Row()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Row(row =>
{
row.Spacing(5);
row.AutoItem().Height(50).Width(50).Background(Colors.Red.Lighten1);
row.AutoItem().Height(50).Width(50).Background(Colors.Green.Lighten1);
row.AutoItem().Height(50).Width(75).Background(Colors.Blue.Lighten1);
});
}
}
[Test]
public void Table()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Table(table =>
{
table.ColumnsDefinition(columns =>
{
columns.RelativeColumn();
columns.RelativeColumn();
columns.RelativeColumn();
});
table.Cell().Height(50).Background(Colors.Red.Lighten1);
table.Cell().Height(50).Background(Colors.Green.Lighten1);
table.Cell().Height(50).Background(Colors.Blue.Lighten1);
table.Cell().ColumnSpan(2).Height(50).Background(Colors.Orange.Lighten1);
});
}
}
[Test]
public void Constrained()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Width(50).Height(50).Background(Colors.Red.Lighten1);
}
}
[Test]
public void Unconstrained()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container
.Width(100)
.Height(100)
.Background(Colors.Grey.Lighten3)
.AlignCenter()
.AlignMiddle()
.Unconstrained()
.Width(50)
.Height(50)
.Background(Colors.Red.Lighten1);
}
}
[Test]
public void Inlined()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Column(column =>
{
column.Spacing(10);
column.Item().Background(Colors.Grey.Lighten3).Text("Default alignment").FontSize(13);
column.Item().Element(ContentWithAlignment(null));
column.Item().Background(Colors.Grey.Lighten3).Text("Left alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(InlinedAlignment.Left));
column.Item().Background(Colors.Grey.Lighten3).Text("Center alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(InlinedAlignment.Center));
column.Item().Background(Colors.Grey.Lighten3).Text("Right alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(InlinedAlignment.Right));
});
static Action<IContainer> ContentWithAlignment(InlinedAlignment? alignment)
{
return container =>
{
container.Inlined(inlined =>
{
inlined.Spacing(5);
inlined.Alignment(alignment);
inlined.Item().Height(50).Width(50).Background(Colors.Red.Lighten1);
inlined.Item().Height(50).Width(75).Background(Colors.Green.Lighten1);
inlined.Item().Height(50).Width(100).Background(Colors.Blue.Lighten1);
inlined.Item().Height(50).Width(125).Background(Colors.Orange.Lighten1);
});
};
}
}
}
[Test]
public void Text()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Column(column =>
{
column.Spacing(10);
column.Item().Background(Colors.Grey.Lighten3).Text("Default alignment").FontSize(13);
column.Item().Element(ContentWithAlignment(null));
column.Item().Background(Colors.Grey.Lighten3).Text("Left alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(HorizontalAlignment.Left));
column.Item().Background(Colors.Grey.Lighten3).Text("Center alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(HorizontalAlignment.Center));
column.Item().Background(Colors.Grey.Lighten3).Text("Right alignment").FontSize(14);
column.Item().Element(ContentWithAlignment(HorizontalAlignment.Right));
});
static Action<IContainer> ContentWithAlignment(HorizontalAlignment? alignment)
{
return container =>
{
container.Text(text =>
{
text.Alignment = alignment; // internal API
text.Span("Lorem ipsum").Bold().FontColor(Colors.Red.Medium);
text.Element().Width(5);
text.Span(Placeholders.LoremIpsum());
});
};
}
}
}
[Test]
public void Decoration()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Decoration(decoration =>
{
decoration.Before().Background(Colors.Green.Lighten1).Padding(5).Text("Before").FontSize(16);
decoration.Content().Background(Colors.Green.Lighten2).Padding(5).Text("Content").FontSize(16);
decoration.After().Background(Colors.Green.Lighten3).Padding(5).Text("After").FontSize(16);
});
}
}
[Test]
public void Dynamic()
{
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProduceImages()
.ShowResults()
.EnableDebugging()
.Render(ContentDirectionTemplate(Content));
void Content(IContainer container)
{
container.Dynamic(new SimpleDynamic());
}
}
class SimpleDynamic : IDynamicComponent<int>
{
public int State { get; set; }
public DynamicComponentComposeResult Compose(DynamicContext context)
{
var content = context.CreateElement(container =>
{
container.Row(row =>
{
row.ConstantItem(50).Background(Colors.Red.Lighten2).Height(50);
row.ConstantItem(75).Background(Colors.Green.Lighten2).Height(50);
row.ConstantItem(100).Background(Colors.Blue.Lighten2).Height(50);
});
});
return new DynamicComponentComposeResult
{
Content = content,
HasMoreContent = false
};
}
}
}
}
-146
View File
@@ -1,146 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using QuestPDF.Elements;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
namespace QuestPDF.Examples
{
public class ProcessRunningTime
{
public TimeSpan FluentTime { get; set; }
public TimeSpan GenerationTime { get; set; }
public float Size { get; set; }
}
public class GenerationBenchmark
{
public const int TestSize = 4096;
[Test]
public void BenchmarkAsync()
{
RunTest(() => Enumerable
.Range(0, TestSize)
.AsParallel() // difference
.Select(GenerateAndCollect)
.ToList());
}
[Test]
public void BenchmarkSync()
{
RunTest(() => Enumerable
.Range(0, TestSize)
.Select(GenerateAndCollect)
.ToList());
}
public void RunTest(Func<IEnumerable<ProcessRunningTime>> handler)
{
var totalFluentTime = TimeSpan.Zero;
var totalGenerationTime = TimeSpan.Zero;
var stopWatch = new Stopwatch();
stopWatch.Start();
var results = handler();
stopWatch.Stop();
foreach (var result in results)
{
totalFluentTime += result.FluentTime;
totalGenerationTime += result.GenerationTime;
}
Console.WriteLine($"Fluent: {totalFluentTime:g}");
Console.WriteLine($"Generation: {totalGenerationTime:g}");
Console.WriteLine($"Total: {stopWatch.Elapsed:g}");
}
static ProcessRunningTime GenerateAndCollect(int attemptNumber)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var container = new Container();
container
.Padding(10)
.MinimalBox()
.Border(1)
.Column(column =>
{
column.Item().Text($"Attempts {attemptNumber}");
const int numberOfRows = 100;
const int numberOfColumns = 10;
for (var y = 0; y < numberOfRows; y++)
{
column.Item().Row(row =>
{
for (var x = 0; x < numberOfColumns; x++)
{
row.RelativeItem()
.Background(Colors.Red.Lighten5)
.Padding(3)
.Background(Colors.Red.Lighten4)
.Padding(3)
.Background(Colors.Red.Lighten3)
.Padding(3)
.Background(Colors.Red.Lighten2)
.Padding(3)
.Background(Colors.Red.Lighten1)
.Padding(3)
.Background(Colors.Red.Medium)
.Padding(3)
.Background(Colors.Red.Darken1)
.Padding(3)
.Background(Colors.Red.Darken2)
.Padding(3)
.Background(Colors.Red.Darken3)
.Padding(3)
.Background(Colors.Red.Darken4)
.Height(3);
}
});
}
});
var fluentTime = stopwatch.Elapsed;
stopwatch.Reset();
stopwatch.Start();
var size = Document
.Create(x => x.Page(page => page.Content().Element(container)))
.GeneratePdf()
.Length;
var generationTime = stopwatch.Elapsed;
return new ProcessRunningTime
{
FluentTime = fluentTime,
GenerationTime = generationTime,
Size = size
};
}
}
}
+1 -55
View File
@@ -1,5 +1,4 @@
using System;
using System.IO;
using System.IO;
using NUnit.Framework;
using QuestPDF.Drawing.Exceptions;
using QuestPDF.Examples.Engine;
@@ -35,21 +34,6 @@ namespace QuestPDF.Examples
});
}
[Test]
public void DynamicImage()
{
RenderingTest
.Create()
.PageSize(450, 350)
.ProducePdf()
.ShowResults()
.Render(page =>
{
page.Padding(25)
.Image(Placeholders.Image);
});
}
[Test]
public void Exception()
{
@@ -63,43 +47,5 @@ namespace QuestPDF.Examples
.Render(page => page.Image("non_existent.png"));
});
}
[Test]
public void ReusingTheSameImageFileShouldBePossible()
{
var fileName = Path.GetTempFileName() + ".jpg";
try
{
var image = Placeholders.Image(300, 100);
using var file = File.Create(fileName);
file.Write(image);
file.Dispose();
RenderingTest
.Create()
.ProducePdf()
.PageSize(PageSizes.A4)
.ShowResults()
.Render(container =>
{
container
.Padding(20)
.Column(column =>
{
column.Spacing(20);
column.Item().Image(fileName);
column.Item().Image(fileName);
column.Item().Image(fileName);
});
});
}
finally
{
File.Delete(fileName);
}
}
}
}
+5 -5
View File
@@ -1,16 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.13.2" />
<PackageReference Include="BenchmarkDotNet" Version="0.13.1" />
<PackageReference Include="microcharts" Version="0.9.5.9" />
<PackageReference Include="nunit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.3.1" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.4.0" />
<PackageReference Include="SkiaSharp" Version="2.80.4" />
<PackageReference Include="Svg.Skia" Version="0.5.10" />
</ItemGroup>
-36
View File
@@ -105,41 +105,5 @@ namespace QuestPDF.Examples
.Row(row => { });
});
}
[Test]
public void RowElementForRelativeHeightDivision()
{
RenderingTest
.Create()
.ProduceImages()
.ShowResults()
.MaxPages(100)
.PageSize(250, 400)
.Render(container =>
{
container
.Padding(25)
.AlignLeft()
.RotateRight()
.Row(row =>
{
row.Spacing(20);
row.RelativeItem(1).Element(Content);
row.RelativeItem(2).Element(Content);
row.RelativeItem(3).Element(Content);
void Content(IContainer container)
{
container
.RotateLeft()
.Border(1)
.Background(Placeholders.BackgroundColor())
.Padding(5)
.Text(Placeholders.Label());
}
});
});
}
}
}
+1 -1
View File
@@ -111,7 +111,7 @@ namespace QuestPDF.Examples
{
page.Margin(50);
page.Content().PaddingVertical(10).Column(column =>
page.Content().Column(column =>
{
column.Item().Element(Title);
column.Item().PageBreak();
+5 -113
View File
@@ -1,8 +1,7 @@
using System;
using System;
using System.Linq;
using System.Text;
using NUnit.Framework;
using QuestPDF.Elements.Text;
using QuestPDF.Examples.Engine;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
@@ -591,7 +590,7 @@ namespace QuestPDF.Examples
text.Span("Complex Unicode structure: ");
text.Span("T̶̖̔͆͆̽̔ḩ̷̼̫̐̈́̀͜͝͝ì̶͇̤͓̱̣͇͓͉̎s̵̡̟̹͍̜͉̗̾͛̈̐́͋͂͝͠ͅ ̴̨͙͍͇̭̒͗̀́͝ì̷̡̺͉̼̏̏̉̌͝s̷͍͙̗̰̖͙̈̑̂̔͑͊̌̓̊̇͜ ̶̛̼͚͊̅͘ṭ̷̨̘̣̙̖͉͌̏̂̅͑̄̽̕͝ȅ̶̲̲̙̭͈̬̣͔̝͔̈́͝s̸̢̯̪̫͓̭̮̓̀͆͜ț̸̢͉̞̥̤̏̌̓͝").FontFamily(Fonts.Calibri).FontColor(Colors.Red.Medium);
text.Span("T̶̖̔͆͆̽̔ḩ̷̼̫̐̈́̀͜͝͝ì̶͇̤͓̱̣͇͓͉̎s̵̡̟̹͍̜͉̗̾͛̈̐́͋͂͝͠ͅ ̴̨͙͍͇̭̒͗̀́͝ì̷̡̺͉̼̏̏̉̌͝s̷͍͙̗̰̖͙̈̑̂̔͑͊̌̓̊̇͜ ̶̛̼͚͊̅͘ṭ̷̨̘̣̙̖͉͌̏̂̅͑̄̽̕͝ȅ̶̲̲̙̭͈̬̣͔̝͔̈́͝s̸̢̯̪̫͓̭̮̓̀͆͜ț̸̢͉̞̥̤̏̌̓͝").FontColor(Colors.Red.Medium);
text.Span(".");
@@ -604,7 +603,7 @@ namespace QuestPDF.Examples
{
RenderingTest
.Create()
.PageSize(250, 100)
.PageSize(500, 100)
.ProduceImages()
.ShowResults()
@@ -614,115 +613,8 @@ namespace QuestPDF.Examples
.Padding(25)
.MinimalBox()
.Background(Colors.Grey.Lighten2)
.Text("خوارزمية ترتيب")
.FontFamily(Fonts.Calibri)
.FontSize(30);
});
}
[Test]
public void FontFallback()
{
RenderingTest
.Create()
.ProduceImages()
.ShowResults()
.RenderDocument(container =>
{
container.Page(page =>
{
page.Margin(50);
page.PageColor(Colors.White);
page.DefaultTextStyle(x => x
.Fallback(y => y.FontFamily("Segoe UI Emoji")
.Fallback(y => y.FontFamily("Microsoft YaHei"))));
page.Size(PageSizes.A4);
page.Content().Text(t =>
{
t.Line("This is normal text.");
t.EmptyLine();
t.Line("Following line should use font fallback:");
t.Line("中文文本");
t.EmptyLine();
t.Line("The following line contains a mix of known and unknown characters.");
t.Line("Mixed line: This 中文 is 文文 a mixed 本 本 line 本 中文文本!");
t.EmptyLine();
t.Line("Emojis work out of the box because of font fallback: 😊😅🥳👍❤😍👌");
});
});
});
}
[Test]
public void WordWrappingStability()
{
// instruction: check if any characters repeat when performing the word-wrapping algorithm
RenderingTest
.Create()
.PageSize(PageSizes.A4)
.ProducePdf()
.ShowResults()
.Render(container =>
{
var text = "Lorem ipsum dolor sit amet consectetuer";
container
.Padding(20)
.Column(column =>
{
column.Spacing(10);
foreach (var width in Enumerable.Range(25, 200))
{
column
.Item()
.MaxWidth(width)
.Background(Colors.Grey.Lighten3)
.Text(text);
}
});
});
}
[Test]
public void TextDirectionality()
{
RenderingTest
.Create()
.PageSize(new PageSize(1000, 500))
.ProducePdf()
.ShowResults()
.Render(container =>
{
var text = "في المعلوماتية أو الرياضيات، خوارزمية الترتيب هي خوارزمية تمكن من تنظيم مجموعة عناصر حسب ترتيب محدد.";
container
.Padding(25)
.ContentFromRightToLeft()
.Column(column =>
{
column.Spacing(20);
foreach (var size in new[] { 36, 34, 32, 30, 15 })
{
column
.Item()
.ShowEntire()
.MaxWidth(size * 25)
.Background(Colors.Grey.Lighten3)
.MinimalBox()
.Background(Colors.Grey.Lighten2)
.Text(text)
.FontSize(20)
.FontFamily("Segoe UI");
}
});
.Text("ينا الألم. في بعض الأحيان ونظراً للالتزامات التي يفرضها علينا")
.FontSize(20);
});
}
}
+5 -5
View File
@@ -7,11 +7,11 @@ using QuestPDF.ReportSample.Layouts;
//ImagePlaceholder.Solid = true;
// var model = DataSource.GetReport();
// var report = new StandardReport(model);
// report.ShowInPreviewer();
//
// return;
var model = DataSource.GetReport();
var report = new StandardReport(model);
report.ShowInPreviewer();
return;
Document
.Create(container =>
+158 -16
View File
@@ -2,6 +2,7 @@
using Avalonia.Platform;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Skia;
using DynamicData;
using SkiaSharp;
namespace QuestPDF.Previewer;
@@ -10,9 +11,10 @@ class InteractiveCanvas : ICustomDrawOperation
{
public Rect Bounds { get; set; }
public ICollection<PreviewPage> Pages { get; set; }
public InspectionElement? InspectionElement { get; set; }
private float Width => (float)Bounds.Width;
private float Height => (float)Bounds.Height;
private float ViewportWidth => (float)Bounds.Width;
private float ViewportHeight => (float)Bounds.Height;
public float Scale { get; private set; } = 1;
public float TranslateX { get; set; }
@@ -28,7 +30,7 @@ class InteractiveCanvas : ICustomDrawOperation
public float TotalHeight => TotalPagesHeight + SafeZone * 2 / Scale;
public float MaxWidth => Pages.Any() ? Pages.Max(x => x.Width) : 0;
public float MaxTranslateY => TotalHeight - Height / Scale;
public float MaxTranslateY => TotalHeight - ViewportHeight / Scale;
public float ScrollPercentY
{
@@ -46,7 +48,7 @@ class InteractiveCanvas : ICustomDrawOperation
{
get
{
var viewPortSize = Height / Scale / TotalHeight;
var viewPortSize = ViewportHeight / Scale / TotalHeight;
return Math.Clamp(viewPortSize, 0, 1);
}
}
@@ -61,19 +63,19 @@ class InteractiveCanvas : ICustomDrawOperation
private void LimitTranslate()
{
if (TotalPagesHeight > Height / Scale)
if (TotalPagesHeight > ViewportHeight / Scale)
{
TranslateY = Math.Min(TranslateY, MaxTranslateY);
TranslateY = Math.Max(TranslateY, 0);
}
else
{
TranslateY = (TotalPagesHeight - Height / Scale) / 2;
TranslateY = (TotalPagesHeight - ViewportHeight / Scale) / 2;
}
if (Width / Scale < MaxWidth)
if (ViewportWidth / Scale < MaxWidth)
{
var maxTranslateX = (Width / 2 - SafeZone) / Scale - MaxWidth / 2;
var maxTranslateX = (ViewportWidth / 2 - SafeZone) / Scale - MaxWidth / 2;
TranslateX = Math.Min(TranslateX, -maxTranslateX);
TranslateX = Math.Max(TranslateX, maxTranslateX);
@@ -104,6 +106,72 @@ class InteractiveCanvas : ICustomDrawOperation
LimitTranslate();
}
public int ActivePage { get; set; } = 1;
public IEnumerable<(int pageNumber, float beginY, float endY)> GetPagePosition()
{
var pageNumber = 1;
var currentPagePosition = SafeZone / Scale;
foreach (var page in Pages)
{
yield return (pageNumber, currentPagePosition, currentPagePosition + page.Height);
currentPagePosition += page.Height + PageSpacing;
pageNumber++;
}
}
public void SetActivePage(float x, float y)
{
y /= Scale;
y += TranslateY;
ActivePage = GetPagePosition().FirstOrDefault(p => p.beginY <= y && y <= p.endY).pageNumber;
}
public void ScrollToInspectionElement(InspectionElement element)
{
var location = element.Location.MinBy(x => x.PageNumber);
var pagePosition = GetPagePosition().ElementAt(location.PageNumber - 1);
var page = Pages.ElementAt(location.PageNumber - 1);
var widthScale = ViewportWidth / location.Width;
var heightScale = ViewportHeight / location.Height;
var targetScale = Math.Min(widthScale, heightScale);
targetScale *= 0.7f; // slightly zoom out to show entire element with padding
Scale = targetScale;
TranslateY = pagePosition.beginY + location.Top + location.Height / 2 - ViewportHeight / Scale / 2;
TranslateX = page.Width / 2 - location.Left - location.Width / 2;
}
public (int pageNumber, float x, float y)? FindClickedPointOnThePage(float x, float y)
{
x -= ViewportWidth / 2;
x /= Scale;
x += TranslateX;
y /= Scale;
y += TranslateY;
var location = GetPagePosition().FirstOrDefault(p => p.beginY <= y && y <= p.endY);
if (location == default)
return null;
var page = Pages.ElementAt(location.pageNumber - 1);
x += page.Width / 2;
if (x < 0 || page.Width < x)
return null;
y -= location.beginY;
return (location.pageNumber, x, y);
}
#endregion
@@ -124,20 +192,32 @@ class InteractiveCanvas : ICustomDrawOperation
var originalMatrix = canvas.TotalMatrix;
canvas.Translate(Width / 2, 0);
canvas.Translate(ViewportWidth / 2, 0);
canvas.Scale(Scale);
canvas.Translate(TranslateX, -TranslateY + SafeZone / Scale);
canvas.Translate(TranslateX, -TranslateY);
var topMatrix = canvas.TotalMatrix;;
var positions = GetPagePosition().ToList();
foreach (var page in Pages)
foreach (var pageIndex in Enumerable.Range(0, Pages.Count))
{
canvas.Translate(-page.Width / 2f, 0);
canvas.SetMatrix(topMatrix);
var page = Pages.ElementAt(pageIndex);
var position = positions.ElementAt(pageIndex);
canvas.Translate(-page.Width / 2f, position.beginY);
DrawBlankPage(canvas, page.Width, page.Height);
canvas.DrawPicture(page.Picture);
canvas.Translate(page.Width / 2f, page.Height + PageSpacing);
DrawInspectionElement(canvas, pageIndex + 1);
}
canvas.SetMatrix(topMatrix);
DrawActivePage(canvas);
canvas.SetMatrix(originalMatrix);
DrawInnerGradient(canvas);
}
@@ -173,7 +253,7 @@ class InteractiveCanvas : ICustomDrawOperation
#region inner viewport gradient
private const int InnerGradientSize = (int)SafeZone;
private static readonly SKColor InnerGradientColor = SKColor.Parse("#666");
private static readonly SKColor InnerGradientColor = SKColor.Parse("#555");
private void DrawInnerGradient(SKCanvas canvas)
{
@@ -195,7 +275,69 @@ class InteractiveCanvas : ICustomDrawOperation
SKShaderTileMode.Clamp)
};
canvas.DrawRect(0, 0, Width, InnerGradientSize, fogPaint);
canvas.DrawRect(0, 0, ViewportWidth, InnerGradientSize, fogPaint);
}
#endregion
#region Interactivity
private void DrawActivePage(SKCanvas canvas)
{
if (ActivePage == default)
return;
var page = Pages.ElementAt(ActivePage - 1);
var pagePosition = GetPagePosition().ElementAt(ActivePage - 1);
var thickness = 6f / Scale;
using var strokePaint = new SKPaint
{
StrokeWidth = thickness,
IsStroke = true,
Color = SKColor.Parse("#000")
};
canvas.DrawRect(- page.Width / 2 -thickness / 2, pagePosition.beginY -thickness / 2, page.Width + thickness, page.Height + thickness, strokePaint);
}
private void DrawInspectionElement(SKCanvas canvas, int pageNumber)
{
if (InspectionElement == null || InspectionElement.Location == null)
return;
var location = InspectionElement.Location.FirstOrDefault(x => x.PageNumber == pageNumber);
if (location == null)
return;
var size = 6 / Scale;
size = Math.Min(size, 3);
using var strokePaint1 = new SKPaint
{
StrokeWidth = size,
IsStroke = true,
Color = SKColor.Parse("#42A5F5")
};
using var strokePaint2 = new SKPaint
{
StrokeWidth = size,
IsStroke = true,
PathEffect = SKPathEffect.CreateDash(new[] { size * 3, size * 3 }, 0),
Color = SKColor.Parse("#1E88E5")
};
using var backgroundPaint = new SKPaint
{
Color = SKColor.Parse("#442196F3"),
};
canvas.DrawRect(location.Left, location.Top, location.Width, location.Height, backgroundPaint);
canvas.DrawRect(location.Left + size / 2, location.Top + size / 2, location.Width - size, location.Height - size, strokePaint1);
canvas.DrawRect(location.Left + size / 2, location.Top + size / 2, location.Width - size, location.Height - size, strokePaint2);
}
#endregion
+45
View File
@@ -0,0 +1,45 @@
<UserControl xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:previewer="clr-namespace:QuestPDF.Previewer"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="QuestPDF.Previewer.MyHierarchy">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Panel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3" Name="Highlight" Background="transparent" DoubleTapped="InputElement_OnDoubleTapped" PointerEnter="Highlight_OnPointerEnter" PointerLeave="Indentation_OnPointerLeave" PointerPressed="Clicked"></Panel>
<Panel Grid.Row="0" Grid.Column="0" Name="Indentation"></Panel>
<Panel Grid.Row="0" Grid.Column="1" Name="Panel" Width="16" Height="16" Margin="0,0,8,0" Background="transparent" PointerPressed="Toggle" PointerEnter="Highlight_OnPointerEnter" PointerLeave="Indentation_OnPointerLeave">
<Viewbox Width="24" Height="24">
<Canvas Width="24" Height="24">
<Path Fill="#AFFF" Name="Icon" />
</Canvas>
</Viewbox>
</Panel>
<Panel Grid.Row="0" Grid.Column="2">
<TextBlock Name="ElementName" FontSize="12" Foreground="#AFFF" Margin="0,6" IsHitTestVisible="False"></TextBlock>
</Panel>
<ItemsRepeater Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Name="Repeater" HorizontalCacheLength="1000000" VerticalCacheLength="100000">
<ItemsRepeater.ItemTemplate>
<DataTemplate DataType="previewer:InspectionElement">
<previewer:MyHierarchy Hierarchy="{Binding}" OnSelected="MyHierarchy_OnOnSelected"></previewer:MyHierarchy>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
</Grid>
</UserControl>
+115
View File
@@ -0,0 +1,115 @@
using System.Windows.Input;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Color = System.Drawing.Color;
namespace QuestPDF.Previewer
{
public partial class MyHierarchy : UserControl
{
public static readonly StyledProperty<InspectionElement> HierarchyProperty =
AvaloniaProperty.Register<MyHierarchy, InspectionElement>(nameof(Hierarchy));
public InspectionElement Hierarchy
{
get => GetValue(HierarchyProperty);
set => SetValue(HierarchyProperty, value);
}
public static readonly StyledProperty<InspectionElement?> SelectionProperty =
AvaloniaProperty.Register<MyHierarchy, InspectionElement?>(nameof(Selection));
public InspectionElement? Selection
{
get => GetValue(SelectionProperty);
set => SetValue(SelectionProperty, value);
}
public event Action<InspectionElement>? OnSelected;
public bool Extended { get; set; }
public MyHierarchy()
{
InitializeComponent();
HierarchyProperty.Changed.Subscribe(x =>
{
Configure();
});
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
Configure();
}
private void Configure()
{
var panel = this.FindControl<Panel>("Panel");
panel.IsVisible = Hierarchy?.Children?.Any() ?? false;
this.FindControl<Panel>("Indentation").Width = (Hierarchy?.Level ?? 0) * 24;
UpdateIcon();
this.FindControl<TextBlock>("ElementName").Text = Hierarchy?.Text;
this.FindControl<TextBlock>("ElementName").Foreground = new SolidColorBrush(Avalonia.Media.Color.Parse(Hierarchy?.FontColor ?? "#FFF"));
}
private const string ExtendedIcon = "M7,15L12,10L17,15H7Z";
private const string CollapsedIcon = "M7,10L12,15L17,10H7Z";
private void Toggle(object? sender, PointerPressedEventArgs e)
{
Extended = !Extended;
UpdateIcon();
this.FindControl<ItemsRepeater>("Repeater").Items = Extended ? Hierarchy?.Children : Array.Empty<InspectionElement>();
}
private void UpdateIcon()
{
var iconControl = this.FindControl<Avalonia.Controls.Shapes.Path>("Icon");
iconControl.Data = new PathGeometry
{
Figures = PathFigures.Parse(Extended ? ExtendedIcon : CollapsedIcon)
};
}
private void InputElement_OnDoubleTapped(object? sender, RoutedEventArgs e)
{
Toggle(null, null);
}
private void Highlight_OnPointerEnter(object? sender, PointerEventArgs e)
{
Cursor = Cursor.Parse("hand");
this.FindControl<Panel>("Highlight").Background = new SolidColorBrush(Avalonia.Media.Color.Parse("#1FFF"));
}
private void Indentation_OnPointerLeave(object? sender, PointerEventArgs e)
{
Cursor = Cursor.Default;
this.FindControl<Panel>("Highlight").Background = new SolidColorBrush(Avalonia.Media.Color.Parse("#0000"));
}
private void Clicked(object? sender, PointerPressedEventArgs e)
{
OnSelected?.Invoke(Hierarchy);
}
private void MyHierarchy_OnOnSelected(InspectionElement selected)
{
OnSelected?.Invoke(selected);
Selection = selected;
}
}
}
+81
View File
@@ -35,6 +35,22 @@ namespace QuestPDF.Previewer
set => SetValue(ScrollViewportSizeProperty, value);
}
public static readonly StyledProperty<InspectionElement> HierarchyProperty = AvaloniaProperty.Register<PreviewerControl, InspectionElement>(nameof(Hierarchy));
public InspectionElement Hierarchy
{
get => GetValue(HierarchyProperty);
set => SetValue(HierarchyProperty, value);
}
public static readonly StyledProperty<InspectionElement> CurrentSelectionProperty = AvaloniaProperty.Register<PreviewerControl, InspectionElement>(nameof(CurrentSelection));
public InspectionElement CurrentSelection
{
get => GetValue(CurrentSelectionProperty);
set => SetValue(CurrentSelectionProperty, value);
}
public PreviewerControl()
{
PagesProperty.Changed.Subscribe(x =>
@@ -49,7 +65,72 @@ namespace QuestPDF.Previewer
InvalidateVisual();
});
CurrentSelectionProperty.Changed.Subscribe(x =>
{
InteractiveCanvas.InspectionElement = CurrentSelection;
//InteractiveCanvas.ScrollToInspectionElement(CurrentSelection);
InvalidateVisual();
});
ClipToBounds = true;
PointerPressed += (sender, args) =>
{
var position = args.GetPosition(this);
InteractiveCanvas.SetActivePage((float)position.X, (float)position.Y);
var clickedPosition = InteractiveCanvas.FindClickedPointOnThePage((float)position.X, (float)position.Y);
if (clickedPosition != null)
FindHighlightedElement(clickedPosition.Value.pageNumber, clickedPosition.Value.x, clickedPosition.Value.y);
InvalidateVisual();
};
}
void FindHighlightedElement(int pageNumber, float x, float y)
{
var possible = FlattenHierarchy(Hierarchy, 0)
.Select(x =>
{
var location = x.element.Location.First(y => y.PageNumber == pageNumber);
return new
{
Element = x.element,
Level = x.level,
Size = location.Width * location.Height
};
})
.ToList();
var minSize = possible.Min(x => x.Size);
CurrentSelection = possible
.Where(x => Math.Abs(x.Size - minSize) < 1)
.OrderByDescending(x => x.Level)
.First()
.Element;
IEnumerable<(InspectionElement element, int level)> FlattenHierarchy(InspectionElement element, int level)
{
var location = element.Location.FirstOrDefault(x => x.PageNumber == pageNumber);
if (location == null)
yield break;
if (x < location.Left || location.Left + location.Width < x)
yield break;
if (y < location.Top || location.Top + location.Height < y)
yield break;
yield return (element, level);
foreach (var childIndex in Enumerable.Range(0, element.Children.Count))
foreach (var nestedChild in FlattenHierarchy(element.Children[childIndex], level + childIndex + 1))
yield return nestedChild;
}
}
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
+113 -55
View File
@@ -3,95 +3,153 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:previewer="clr-namespace:QuestPDF.Previewer"
xmlns:visualBasic="clr-namespace:Microsoft.VisualBasic;assembly=Microsoft.VisualBasic.Core"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:Class="QuestPDF.Previewer.PreviewerWindow"
x:DataType="previewer:PreviewerWindowViewModel"
x:CompileBindings="True"
WindowStartupLocation="CenterScreen"
ExtendClientAreaToDecorationsHint="true"
ExtendClientAreaTitleBarHeightHint="-1"
Background="#666"
ExtendClientAreaTitleBarHeightHint="56"
Background="#555"
Icon="/Resources/Logo.png"
UseLayoutRounding="True"
Title="QuestPDF Document Preview">
<Window.Styles>
<Style Selector="Button.actions">
<Style Selector=".MainMenu TextBlock">
<Setter Property="Foreground" Value="#AFFF" />
<Setter Property="Margin" Value="0,0,16,0" />
<Setter Property="FontSize" Value="12" />
</Style>
<Style Selector=".MainMenu TextBlock:pointerover">
<Setter Property="Foreground" Value="#FFF" />
<Setter Property="TextDecorations" Value="Underline" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<Style Selector="Button.actions">
<Setter Property="VerticalAlignment" Value="Bottom"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
<Setter Property="Padding" Value="10"/>
<Setter Property="CornerRadius" Value="100"/>
<Setter Property="Background" Value="#888"/>
<Setter Property="Padding" Value="12" />
<Setter Property="Margin" Value="-1" />
<Setter Property="Background" Value="transparent"/>
</Style>
<Style Selector="Button.actions Path">
<Setter Property="Fill" Value="#8FFF"/>
</Style>
<Style Selector="Button.active Path">
<Setter Property="Fill" Value="#FFFF"/>
</Style>
<Style Selector="Button:pointerover Path">
<Setter Property="Fill" Value="#FFFF"/>
</Style>
<Style Selector="Button:pointerover /template/ ContentPresenter">
<Setter Property="Background" Value="#999"/>
<Setter Property="Background" Value="#333"/>
</Style>
</Window.Styles>
</Window.Styles>
<Panel>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="32" />
<RowDefinition Height="56" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition MinWidth="300" MaxWidth="500" Width="300" />
<ColumnDefinition Width="4" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
VerticalAlignment="Center" HorizontalAlignment="Center"
TextAlignment="Center" Text="QuestPDF Previewer" FontSize="14" Foreground="#DFFF" FontWeight="Regular" IsHitTestVisible="False" />
<previewer:PreviewerControl Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
<Panel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="5" Background="#333">
<StackPanel Orientation="Horizontal">
<Image Source="/Resources/Logo.png" Width="32" Height="32" Margin="12,12,20,12"></Image>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock
VerticalAlignment="Center" HorizontalAlignment="Left" Margin="0,0,0,4"
TextAlignment="Center" Text="QuestPDF Previewer" FontSize="16" Foreground="#FFF" FontWeight="SemiBold" />
<StackPanel Orientation="Horizontal" Classes="MainMenu">
<TextBlock Text="Getting Started" />
<TextBlock Text="Documentation" />
<TextBlock Text="GitHub" />
<TextBlock Text="Sponsor project" />
</StackPanel>
</StackPanel>
</StackPanel>
</Panel>
<Grid Grid.Row="1" Grid.Column="0" Background="#444">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="32" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Panel Grid.Row="0">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Margin="16,8"
TextAlignment="Center" Text="Document hierarchy" Foreground="#DFFF" FontWeight="SemiBold" IsHitTestVisible="False" />
</Panel>
<Panel Grid.Row="1">
<ScrollViewer>
<previewer:MyHierarchy Hierarchy="{Binding Items}" Margin="-8,0,0,0" Selection="{Binding SelectedItem, Mode=TwoWay}"></previewer:MyHierarchy>
</ScrollViewer>
</Panel>
<Panel Grid.Row="3">
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Left" Margin="16,8"
TextAlignment="Center" Text="Selected element properties" Foreground="#DFFF" FontWeight="SemiBold" IsHitTestVisible="False" />
</Panel>
<Panel Grid.Row="4">
<ItemsRepeater Items="{Binding SelectedItem.Metadata}" Margin="16, 2">
<ItemsRepeater.ItemTemplate>
<DataTemplate DataType="previewer:Metadata">
<Grid Margin="0, 4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="16" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Label}" Foreground="#AFFF" FontSize="12" />
<TextBlock Grid.Column="2" Text="{Binding Value}" Foreground="#AFFF" FontSize="12" />
</Grid>
</DataTemplate>
</ItemsRepeater.ItemTemplate>
</ItemsRepeater>
</Panel>
</Grid>
<GridSplitter Grid.Column="1" Grid.Row="1" Background="#444" ResizeDirection="Columns" />
<previewer:PreviewerControl Grid.Row="1" Grid.Column="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
CurrentScroll="{Binding CurrentScroll, Mode=TwoWay}"
ScrollViewportSize="{Binding ScrollViewportSize, Mode=OneWayToSource}"
CurrentSelection="{Binding SelectedItem, Mode=TwoWay}"
Hierarchy="{Binding Items}"
Pages="{Binding Pages, Mode=OneWay}" />
<StackPanel Grid.Row="1" Grid.Column="0" Orientation="Vertical" VerticalAlignment="Bottom" Spacing="16" Margin="32">
<Button Classes="actions"
Command="{Binding ShowPdfCommand, Mode=OneTime}"
IsVisible="{Binding !!Pages.Count}"
ToolTip.Tip="Generates PDF file and shows it in the default browser. Useful for testing compatibility and interactive links.">
<Viewbox Width="24" Height="24">
<Canvas Width="24" Height="24">
<Path Fill="White" Data="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H13C12.59,21.75 12.2,21.44 11.86,21.1C11.53,20.77 11.25,20.4 11,20H6V4H13V9H18V10.18C18.71,10.34 19.39,10.61 20,11V8L14,2M20.31,18.9C21.64,16.79 21,14 18.91,12.68C16.8,11.35 14,12 12.69,14.08C11.35,16.19 12,18.97 14.09,20.3C15.55,21.23 17.41,21.23 18.88,20.32L22,23.39L23.39,22L20.31,18.9M16.5,19A2.5,2.5 0 0,1 14,16.5A2.5,2.5 0 0,1 16.5,14A2.5,2.5 0 0,1 19,16.5A2.5,2.5 0 0,1 16.5,19Z" />
</Canvas>
</Viewbox>
</Button>
<Button Classes="actions"
Command="{Binding ShowDocumentationCommand, Mode=OneTime}"
ToolTip.Tip="Opens official QuestPDF documentation">
<Viewbox Width="24" Height="24">
<Canvas Width="24" Height="24">
<Path Fill="White" Data="M19 1L14 6V17L19 12.5V1M21 5V18.5C19.9 18.15 18.7 18 17.5 18C15.8 18 13.35 18.65 12 19.5V6C10.55 4.9 8.45 4.5 6.5 4.5C4.55 4.5 2.45 4.9 1 6V20.65C1 20.9 1.25 21.15 1.5 21.15C1.6 21.15 1.65 21.1 1.75 21.1C3.1 20.45 5.05 20 6.5 20C8.45 20 10.55 20.4 12 21.5C13.35 20.65 15.8 20 17.5 20C19.15 20 20.85 20.3 22.25 21.05C22.35 21.1 22.4 21.1 22.5 21.1C22.75 21.1 23 20.85 23 20.6V6C22.4 5.55 21.75 5.25 21 5M10 18.41C8.75 18.09 7.5 18 6.5 18C5.44 18 4.18 18.19 3 18.5V7.13C3.91 6.73 5.14 6.5 6.5 6.5C7.86 6.5 9.09 6.73 10 7.13V18.41Z" />
</Canvas>
</Viewbox>
</Button>
<Button Classes="actions"
Command="{Binding SponsorProjectCommand, Mode=OneTime}"
ToolTip.Tip="Do you like QuestPDF? Please consider sponsoring the project. It really helps!">
<Viewbox Width="24" Height="24">
<Canvas Width="24" Height="24">
<Path Fill="White" Data="M12,21.1L10.5,22.4C3.9,16.5 0.5,13.4 0.5,9.6C0.5,8.4 0.9,7.3 1.5,6.4C1.5,6.6 1.5,6.8 1.5,7C1.5,11.7 5.4,15.2 12,21.1M13.6,17C18.3,12.7 21.5,9.9 21.6,7C21.6,5 20.1,3.5 18.1,3.5C16.5,3.5 15,4.5 14.5,5.9H12.6C12,4.5 10.5,3.5 9,3.5C7,3.5 5.5,5 5.5,7C5.5,9.9 8.6,12.7 13.4,17L13.5,17.1M18,1.5C21.1,1.5 23.5,3.9 23.5,7C23.5,10.7 20.1,13.8 13.5,19.8C6.9,13.9 3.5,10.8 3.5,7C3.5,3.9 5.9,1.5 9,1.5C10.7,1.5 12.4,2.3 13.5,3.6C14.6,2.3 16.3,1.5 18,1.5Z" />
</Canvas>
</Viewbox>
</Button>
</StackPanel>
<ScrollBar Grid.Row="1" Grid.Column="1"
Orientation="Vertical"
AllowAutoHide="False"
Minimum="0" Maximum="1"
IsVisible="{Binding VerticalScrollbarVisible, Mode=OneWay}"
Value="{Binding CurrentScroll, Mode=TwoWay}"
ViewportSize="{Binding ScrollViewportSize, Mode=OneWay}"></ScrollBar>
<ScrollBar Grid.Row="1" Grid.Column="3"
Orientation="Vertical"
AllowAutoHide="False"
Minimum="0" Maximum="1"
IsVisible="{Binding VerticalScrollbarVisible, Mode=OneWay}"
Value="{Binding CurrentScroll, Mode=TwoWay}"
ViewportSize="{Binding ScrollViewportSize, Mode=OneWay}"></ScrollBar>
</Grid>
</Panel>
</Window>
+2 -1
View File
@@ -1,4 +1,5 @@
using Avalonia.Controls;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace QuestPDF.Previewer
+89 -1
View File
@@ -1,5 +1,7 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using Avalonia;
using ReactiveUI;
using Unit = System.Reactive.Unit;
using Avalonia.Threading;
@@ -49,8 +51,10 @@ namespace QuestPDF.Previewer
CommunicationService.Instance.OnDocumentRefreshed += HandleUpdatePreview;
ShowPdfCommand = ReactiveCommand.Create(ShowPdf);
ShowDocumentationCommand = ReactiveCommand.Create(() => OpenLink("https://www.questpdf.com/api-reference/index.html"));
ShowDocumentationCommand = ReactiveCommand.Create(() => OpenLink("https://www.questpdf.com/documentation/api-reference.html"));
SponsorProjectCommand = ReactiveCommand.Create(() => OpenLink("https://github.com/sponsors/QuestPDF"));
LoadItems();
}
private void ShowPdf()
@@ -85,5 +89,89 @@ namespace QuestPDF.Previewer
foreach (var page in oldPages)
page.Picture.Dispose();
}
private InspectionElement _selectedItem;
public InspectionElement SelectedItem
{
get => _selectedItem;
set => this.RaiseAndSetIfChanged(ref _selectedItem, value);
}
private InspectionElement items;
public InspectionElement Items
{
get => items;
set => this.RaiseAndSetIfChanged(ref items, value);
}
public void LoadItems()
{
var text = File.ReadAllText("hierarchy.json");
Items = JsonSerializer.Deserialize<InspectionElement>(text);
UpdateLevel(Items);
}
private void UpdateLevel(InspectionElement root)
{
var currentLevel = 1;
Traverse(root);
void Traverse(InspectionElement element)
{
element.Level = currentLevel;
currentLevel++;
element.Children.ForEach(Traverse);
currentLevel--;
}
}
}
public class InspectionElementLocation
{
public int PageNumber { get; set; }
public float Top { get; set; }
public float Left { get; set; }
public float Width { get; set; }
public float Height { get; set; }
}
public class Metadata
{
public string Label { get; set; }
public string Value { get; set; }
public Metadata(string label, string value)
{
Label = label;
Value = value;
}
}
public class InspectionElement
{
public string Element { get; set; }
public List<InspectionElementLocation> Location { get; set; }
public Dictionary<string, string> Properties { get; set; }
public List<InspectionElement> Children { get; set; }
public int Level { get; set; }
public string FontColor => Element == "DebugPointer" ? "#FFF" : "#AFFF";
public string Text => Element == "DebugPointer" ? Properties.First(x => x.Key == "Target").Value : Element;
public bool Expanded { get; set; }
public IList<Metadata> Metadata => ListMetadata().ToList();
public IEnumerable<Metadata> ListMetadata()
{
yield return new Metadata("Element name", Element);
yield return new Metadata("Position left", Location[0].Left.ToString("N2"));
yield return new Metadata("Position top", Location[0].Top.ToString("N2"));
yield return new Metadata("Width", Location[0].Width.ToString("N2"));
yield return new Metadata("Height", Location[0].Height.ToString("N2"));
foreach (var property in Properties)
yield return new Metadata(property.Key, property.Value);
}
}
}
+4 -1
View File
@@ -4,7 +4,7 @@
<Authors>MarcinZiabek</Authors>
<Company>CodeFlint</Company>
<PackageId>QuestPDF.Previewer</PackageId>
<Version>2022.11.0</Version>
<Version>2022.6.0</Version>
<PackAsTool>true</PackAsTool>
<ToolCommandName>questpdf-previewer</ToolCommandName>
<PackageDescription>QuestPDF is an open-source, modern and battle-tested library that can help you with generating PDF documents by offering friendly, discoverable and predictable C# fluent API.</PackageDescription>
@@ -38,6 +38,9 @@
<Visible>false</Visible>
<PackagePath>\</PackagePath>
</None>
<None Update="hierarchy.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
File diff suppressed because one or more lines are too long
@@ -68,11 +68,9 @@ namespace QuestPDF.ReportSample.Layouts
var lengthStyle = TextStyle.Default.FontColor(Colors.Grey.Medium);
text.TotalPagesWithinSection(locationName).Style(lengthStyle).Format(x =>
{
var formatted = x == 1 ? "1 page long" : $"{x} pages long";
return $" ({formatted})";
});
text.Span(" (").Style(lengthStyle);
text.TotalPagesWithinSection(locationName).Style(lengthStyle).Format(x => x == 1 ? "1 page long" : $"{x} pages long");
text.Span(")").Style(lengthStyle);
});
});
}
+2 -2
View File
@@ -51,7 +51,7 @@ namespace QuestPDF.ReportSample
Content = documentContainer.Compose();
PageContext = new PageContext();
DocumentGenerator.RenderPass(PageContext, new FreeCanvas(), Content, null);
DocumentGenerator.RenderPass(PageContext, new FreeCanvas(), Content, Metadata, null);
var sw = new Stopwatch();
sw.Start();
@@ -69,7 +69,7 @@ namespace QuestPDF.ReportSample
[Benchmark]
public void GenerationTest()
{
DocumentGenerator.RenderPass(PageContext, new FreeCanvas(), Content, null);
DocumentGenerator.RenderPass(PageContext, new FreeCanvas(), Content, Metadata, null);
}
}
}
+3 -2
View File
@@ -48,10 +48,11 @@ namespace QuestPDF.ReportSample
Report.Compose(container);
var content = container.Compose();
var metadata = Report.GetMetadata();
var pageContext = new PageContext();
DocumentGenerator.RenderPass(pageContext, new FreeCanvas(), content, null);
DocumentGenerator.RenderPass(pageContext, new FreeCanvas(), content, null);
DocumentGenerator.RenderPass(pageContext, new FreeCanvas(), content, metadata, null);
DocumentGenerator.RenderPass(pageContext, new FreeCanvas(), content, metadata, null);
}
}
}
+3 -3
View File
@@ -6,8 +6,8 @@ namespace QuestPDF.ReportSample
{
public static class Typography
{
public static TextStyle Title => TextStyle.Default.FontFamily(Fonts.Lato).FontColor(Colors.Blue.Darken3).FontSize(26).Black();
public static TextStyle Headline => TextStyle.Default.FontFamily(Fonts.Lato).FontColor(Colors.Blue.Medium).FontSize(16).SemiBold();
public static TextStyle Normal => TextStyle.Default.FontFamily(Fonts.Lato).FontColor(Colors.Black).FontSize(10).LineHeight(1.2f);
public static TextStyle Title => TextStyle.Default.FontFamily(Fonts.Calibri).FontColor(Colors.Blue.Darken3).FontSize(26).Black();
public static TextStyle Headline => TextStyle.Default.FontFamily(Fonts.Calibri).FontColor(Colors.Blue.Medium).FontSize(16).SemiBold();
public static TextStyle Normal => TextStyle.Default.FontFamily(Fonts.Verdana).FontColor(Colors.Black).FontSize(10).LineHeight(1.2f);
}
}
-40
View File
@@ -153,9 +153,7 @@ namespace QuestPDF.UnitTests
Ratio = 2f
})
.DrawElement(new Size(500, 200))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(400, 200))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
@@ -170,45 +168,7 @@ namespace QuestPDF.UnitTests
Ratio = 2f
})
.DrawElement(new Size(400, 300))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(400, 200))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
[Test]
public void DrawChild_PerWidth_RightToLeft()
{
TestPlan
.For(x => new AspectRatio
{
Child = x.CreateChild(),
Option = AspectRatioOption.FitArea,
Ratio = 2f,
ContentDirection = ContentDirection.RightToLeft
})
.DrawElement(new Size(500, 200))
.ExpectCanvasTranslate(100, 0)
.ExpectChildDraw(new Size(400, 200))
.ExpectCanvasTranslate(-100, 0)
.CheckDrawResult();
}
[Test]
public void DrawChild_PerHeight_RightToLeft()
{
TestPlan
.For(x => new AspectRatio
{
Child = x.CreateChild(),
Option = AspectRatioOption.FitArea,
Ratio = 2f,
ContentDirection = ContentDirection.RightToLeft
})
.DrawElement(new Size(400, 300))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(400, 200))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
}
-38
View File
@@ -35,9 +35,7 @@ namespace QuestPDF.UnitTests
})
.MeasureElement(new Size(400, 300))
.ExpectChildMeasure(expectedInput: new Size(400, 300), returns: SpacePlan.PartialRender(200, 100))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(200, 100))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
@@ -51,43 +49,7 @@ namespace QuestPDF.UnitTests
})
.MeasureElement(new Size(500, 400))
.ExpectChildMeasure(expectedInput: new Size(500, 400), returns: SpacePlan.FullRender(300, 200))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(300, 200))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
[Test]
public void Measure_PartialRender_RightToLeft()
{
TestPlan
.For(x => new MinimalBox
{
Child = x.CreateChild(),
ContentDirection = ContentDirection.RightToLeft
})
.MeasureElement(new Size(400, 300))
.ExpectChildMeasure(expectedInput: new Size(400, 300), returns: SpacePlan.PartialRender(200, 100))
.ExpectCanvasTranslate(200, 0)
.ExpectChildDraw(new Size(200, 100))
.ExpectCanvasTranslate(-200, 0)
.CheckDrawResult();
}
[Test]
public void Measure_FullRender_RightToLeft()
{
TestPlan
.For(x => new MinimalBox
{
Child = x.CreateChild(),
ContentDirection = ContentDirection.RightToLeft
})
.MeasureElement(new Size(500, 400))
.ExpectChildMeasure(expectedInput: new Size(500, 400), returns: SpacePlan.FullRender(350, 200))
.ExpectCanvasTranslate(150, 0)
.ExpectChildDraw(new Size(350, 200))
.ExpectCanvasTranslate(-150, 0)
.CheckDrawResult();
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.7.0" />
<PackageReference Include="FluentAssertions" Version="6.1.0" />
<PackageReference Include="nunit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.0" />
+6 -6
View File
@@ -195,7 +195,7 @@ namespace QuestPDF.UnitTests.TestEngine
public TestPlan CheckMeasureResult(SpacePlan expected)
{
Element.InjectDependencies(null, Canvas);
Element.VisitChildren(x => x?.Initialize(null, Canvas));
var actual = Element.Measure(OperationInput);
@@ -210,7 +210,7 @@ namespace QuestPDF.UnitTests.TestEngine
public TestPlan CheckDrawResult()
{
Element.InjectDependencies(null, Canvas);
Element.VisitChildren(x => x?.Initialize(null, Canvas));
Element.Draw(OperationInput);
return this;
}
@@ -253,10 +253,10 @@ namespace QuestPDF.UnitTests.TestEngine
availableSpace ??= new Size(400, 300);
var canvas = new FreeCanvas();
value.InjectDependencies(null, canvas);
value.VisitChildren(x => x.Initialize(null, canvas));
var valueMeasure = value.Measure(availableSpace.Value);
expected.InjectDependencies(null, canvas);
expected.VisitChildren(x => x.Initialize(null, canvas));
var expectedMeasure = expected.Measure(availableSpace.Value);
valueMeasure.Should().BeEquivalentTo(expectedMeasure);
@@ -267,11 +267,11 @@ namespace QuestPDF.UnitTests.TestEngine
availableSpace ??= new Size(400, 300);
var valueCanvas = new OperationRecordingCanvas();
value.InjectDependencies(null, valueCanvas);
value.VisitChildren(x => x.Initialize(null, valueCanvas));
value.Draw(availableSpace.Value);
var expectedCanvas = new OperationRecordingCanvas();
expected.InjectDependencies(null, expectedCanvas);
expected.VisitChildren(x => x.Initialize(null, expectedCanvas));
expected.Draw(availableSpace.Value);
valueCanvas.Operations.Should().BeEquivalentTo(expectedCanvas.Operations);
-38
View File
@@ -77,9 +77,7 @@ namespace QuestPDF.UnitTests
})
.DrawElement(new Size(900, 800))
.ExpectChildMeasure(Size.Max, SpacePlan.PartialRender(1200, 1600))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(1200, 1600))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
@@ -93,43 +91,7 @@ namespace QuestPDF.UnitTests
})
.DrawElement(new Size(900, 800))
.ExpectChildMeasure(Size.Max, SpacePlan.FullRender(1600, 1000))
.ExpectCanvasTranslate(0, 0)
.ExpectChildDraw(new Size(1600, 1000))
.ExpectCanvasTranslate(0, 0)
.CheckDrawResult();
}
[Test]
public void Draw_WhenChildPartiallyRenders_RightToLeft()
{
TestPlan
.For(x => new Unconstrained
{
Child = x.CreateChild(),
ContentDirection = ContentDirection.RightToLeft
})
.DrawElement(new Size(900, 800))
.ExpectChildMeasure(Size.Max, SpacePlan.PartialRender(1200, 1600))
.ExpectCanvasTranslate(-1200, 0)
.ExpectChildDraw(new Size(1200, 1600))
.ExpectCanvasTranslate(1200, 0)
.CheckDrawResult();
}
[Test]
public void Draw_WhenChildFullyRenders_RightToLeft()
{
TestPlan
.For(x => new Unconstrained
{
Child = x.CreateChild(),
ContentDirection = ContentDirection.RightToLeft
})
.DrawElement(new Size(900, 800))
.ExpectChildMeasure(Size.Max, SpacePlan.FullRender(1600, 1000))
.ExpectCanvasTranslate(-1600, 0)
.ExpectChildDraw(new Size(1600, 1000))
.ExpectCanvasTranslate(1600, 0)
.CheckDrawResult();
}
+1
View File
@@ -16,6 +16,7 @@ namespace QuestPDF.Drawing
var container = new Container();
container
.DebugPointer("Document")
.Column(column =>
{
Pages
+240 -43
View File
@@ -1,7 +1,9 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using QuestPDF.Drawing.Exceptions;
using QuestPDF.Drawing.Proxy;
using QuestPDF.Elements;
@@ -10,6 +12,8 @@ using QuestPDF.Elements.Text.Items;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace QuestPDF.Drawing
{
@@ -65,22 +69,232 @@ namespace QuestPDF.Drawing
document.Compose(container);
var content = container.Compose();
ApplyDefaultTextStyle(content, TextStyle.LibraryDefault);
ApplyContentDirection(content, ContentDirection.LeftToRight);
var debuggingState = Settings.EnableDebugging ? ApplyDebugging(content) : null;
var metadata = document.GetMetadata();
var pageContext = new PageContext();
var debuggingState = metadata.ApplyDebugging ? ApplyDebugging(content) : null;
if (Settings.EnableCaching)
if (metadata.ApplyCaching)
ApplyCaching(content);
var pageContext = new PageContext();
RenderPass(pageContext, new FreeCanvas(), content, debuggingState);
RenderPass(pageContext, canvas, content, debuggingState);
RenderPass(pageContext, new FreeCanvas(), content, metadata, debuggingState);
if (metadata.ApplyInspection)
ApplyInspection(content);
RenderPass(pageContext, canvas, content, metadata, debuggingState);
if (metadata.ApplyInspection)
{
var x = TraverseStatisticsToJson(content);
var y = JsonSerializer.Serialize(x);
}
}
internal static string TraverseStructure(Element container)
{
var builder = new StringBuilder();
var nestingLevel = 0;
Traverse(container);
return builder.ToString();
void Traverse(Element item)
{
var indent = new string(' ', nestingLevel * 4);
var title = item.GetType().Name;
builder.AppendLine(indent + title);
nestingLevel++;
foreach (var child in item.GetChildren())
Traverse(child);
nestingLevel--;
}
}
internal static string TraverseStatistics(Element container, int pageNumber)
{
var builder = new StringBuilder();
var nestingLevel = 0;
Traverse(container);
return builder.ToString();
void Traverse(Element item)
{
if (item is DebuggingProxy or CacheProxy or Container)
{
Traverse(item.GetChildren().First());
return;
}
var inspectionItem = item as InspectionProxy;
if (inspectionItem == null)
{
var children = item.GetChildren().ToList();
if (children.Count > 1)
nestingLevel++;
children.ForEach(Traverse);
if (children.Count > 1)
nestingLevel--;
return;
}
if (!inspectionItem.Statistics.ContainsKey(pageNumber))
return;
var statistics = inspectionItem.Statistics[pageNumber];
var indent = new string(' ', nestingLevel * 4);
var title = statistics.Element.GetType().Name;
builder.AppendLine(indent + title);
builder.AppendLine(indent + new string('-', title.Length));
builder.AppendLine(indent + "Size: " + statistics.Size);
builder.AppendLine(indent + "Position: " + statistics.Position);
foreach (var configuration in DebuggingState.GetElementConfiguration(statistics.Element))
builder.AppendLine(indent + configuration);
builder.AppendLine();
Traverse(inspectionItem.Child);
}
}
internal static void RenderPass<TCanvas>(PageContext pageContext, TCanvas canvas, Container content, DebuggingState? debuggingState)
internal static InspectionElement TraverseStatisticsToJson(Element container)
{
return Traverse(container);
InspectionElement? Traverse(Element item)
{
InspectionElement? result = null;
Element currentItem = item;
while (true)
{
if (currentItem is InspectionProxy proxy)
{
if (proxy.Child.GetType() == typeof(Container))
{
currentItem = proxy.Child;
continue;
}
var statistics = GetInspectionElement(proxy);
if (statistics == null)
return null;
if (result == null)
{
result = statistics;
}
else
{
result.Children.Add(statistics);
}
currentItem = proxy.Child;
}
else
{
var children = currentItem.GetChildren().ToList();
if (children.Count == 0)
{
return result;
}
else if (children.Count == 1)
{
currentItem = children.First();
continue;
}
else
{
children
.Select(Traverse)
.Where(x => x != null)
.ToList()
.ForEach(result.Children.Add);
return result;
}
}
}
}
static InspectionElement? GetInspectionElement(InspectionProxy inspectionProxy)
{
var locations = inspectionProxy
.Statistics
.Keys
.Select(x =>
{
var statistics = inspectionProxy.Statistics[x];
return new InspectionElementLocation
{
PageNumber = x,
Top = statistics.Position.Y,
Left = statistics.Position.X,
Width = statistics.Size.Width,
Height = statistics.Size.Height,
};
})
.ToList();
return new InspectionElement
{
Element = inspectionProxy.Child.GetType().Name,
Location = locations,
Properties = GetElementConfiguration(inspectionProxy.Child),
Children = new List<InspectionElement>()
};
}
static Dictionary<string, string> GetElementConfiguration(IElement element)
{
return element
.GetType()
.GetProperties()
.Select(x => new
{
Property = x.Name.PrettifyName(),
Value = x.GetValue(element)
})
.Where(x => !(x.Value is IElement))
.Where(x => x.Value is string || !(x.Value is IEnumerable))
.Where(x => !(x.Value is TextStyle))
.ToDictionary(x => x.Property, x => FormatValue(x.Value));
string FormatValue(object value)
{
const int maxLength = 100;
var text = value?.ToString() ?? "-";
if (text.Length < maxLength)
return text;
return text.AsSpan(0, maxLength).ToString() + "...";
}
}
}
internal static void RenderPass<TCanvas>(PageContext pageContext, TCanvas canvas, Container content, DocumentMetadata documentMetadata, DebuggingState? debuggingState)
where TCanvas : ICanvas, IRenderingCanvas
{
InjectDependencies(content, pageContext, canvas);
content.VisitChildren(x => x?.Initialize(pageContext, canvas));
content.VisitChildren(x => (x as IStateResettable)?.ResetState());
canvas.BeginDocument();
@@ -113,7 +327,7 @@ namespace QuestPDF.Drawing
canvas.EndPage();
if (currentPage >= Settings.DocumentLayoutExceptionThreshold)
if (currentPage >= documentMetadata.DocumentLayoutExceptionThreshold)
{
canvas.EndDocument();
ThrowLayoutException();
@@ -130,8 +344,8 @@ namespace QuestPDF.Drawing
void ThrowLayoutException()
{
var message = $"Composed layout generates infinite document. This may happen in two cases. " +
$"1) Your document and its layout configuration is correct but the content takes more than {Settings.DocumentLayoutExceptionThreshold} pages. " +
$"In this case, please increase the value {nameof(QuestPDF)}.{nameof(Settings)}.{nameof(Settings.DocumentLayoutExceptionThreshold)} static property. " +
$"1) Your document and its layout configuration is correct but the content takes more than {documentMetadata.DocumentLayoutExceptionThreshold} pages. " +
$"In this case, please increase the value {nameof(DocumentMetadata)}.{nameof(DocumentMetadata.DocumentLayoutExceptionThreshold)} property configured in the {nameof(IDocument.GetMetadata)} method. " +
$"2) The layout configuration of your document is invalid. Some of the elements require more space than is provided." +
$"Please analyze your documents structure to detect this element and fix its size constraints.";
@@ -141,18 +355,6 @@ namespace QuestPDF.Drawing
}
}
internal static void InjectDependencies(this Element content, IPageContext pageContext, ICanvas canvas)
{
content.VisitChildren(x =>
{
if (x == null)
return;
x.PageContext = pageContext;
x.Canvas = canvas;
});
}
private static void ApplyCaching(Container content)
{
content.VisitChildren(x =>
@@ -168,28 +370,18 @@ namespace QuestPDF.Drawing
content.VisitChildren(x =>
{
x.CreateProxy(y => new DebuggingProxy(debuggingState, y));
x.CreateProxy(y => y is ElementProxy ? y : new DebuggingProxy(debuggingState, y));
});
return debuggingState;
}
internal static void ApplyContentDirection(this Element? content, ContentDirection direction)
private static void ApplyInspection(Container content)
{
if (content == null)
return;
if (content is ContentDirectionSetter contentDirectionSetter)
content.VisitChildren(x =>
{
ApplyContentDirection(contentDirectionSetter.Child, contentDirectionSetter.ContentDirection);
return;
}
if (content is IContentDirectionAware contentDirectionAware)
contentDirectionAware.ContentDirection = direction;
foreach (var child in content.GetChildren())
ApplyContentDirection(child, direction);
x.CreateProxy(y => y is ElementProxy ? y : new InspectionProxy(y));
});
}
internal static void ApplyDefaultTextStyle(this Element? content, TextStyle documentDefaultTextStyle)
@@ -203,7 +395,7 @@ namespace QuestPDF.Drawing
{
if (textBlockItem is TextBlockSpan textSpan)
{
textSpan.Style = textSpan.Style.ApplyGlobalStyle(documentDefaultTextStyle);
textSpan.Style.ApplyGlobalStyle(documentDefaultTextStyle);
}
else if (textBlockItem is TextBlockElement textElement)
{
@@ -215,13 +407,18 @@ namespace QuestPDF.Drawing
}
if (content is DynamicHost dynamicHost)
dynamicHost.TextStyle = dynamicHost.TextStyle.ApplyGlobalStyle(documentDefaultTextStyle);
dynamicHost.TextStyle.ApplyGlobalStyle(documentDefaultTextStyle);
var targetTextStyle = documentDefaultTextStyle;
if (content is DefaultTextStyle defaultTextStyleElement)
documentDefaultTextStyle = defaultTextStyleElement.TextStyle.ApplyGlobalStyle(documentDefaultTextStyle);
{
defaultTextStyleElement.TextStyle.ApplyParentStyle(documentDefaultTextStyle);
targetTextStyle = defaultTextStyleElement.TextStyle;
}
foreach (var child in content.GetChildren())
ApplyDefaultTextStyle(child, documentDefaultTextStyle);
ApplyDefaultTextStyle(child, targetTextStyle);
}
}
}
+8 -20
View File
@@ -1,5 +1,4 @@
using System;
using QuestPDF.Infrastructure;
namespace QuestPDF.Drawing
{
@@ -19,26 +18,15 @@ namespace QuestPDF.Drawing
public DateTime CreationDate { get; set; } = DateTime.Now;
public DateTime ModifiedDate { get; set; } = DateTime.Now;
[Obsolete("This API has been moved since version 2022.9. Please use the QuestPDF.Settings.DocumentLayoutExceptionThreshold static property.")]
public int DocumentLayoutExceptionThreshold
{
get => Settings.DocumentLayoutExceptionThreshold;
set => Settings.DocumentLayoutExceptionThreshold = value;
}
/// <summary>
/// If the number of generated pages exceeds this threshold
/// (likely due to infinite layout), the exception is thrown.
/// </summary>
public int DocumentLayoutExceptionThreshold { get; set; } = 250;
[Obsolete("This API has been moved since version 2022.9. Please use the QuestPDF.Settings.EnableCaching static property.")]
public bool ApplyCaching
{
get => Settings.EnableCaching;
set => Settings.EnableCaching = value;
}
[Obsolete("This API has been moved since version 2022.9. Please use the QuestPDF.Settings.EnableDebugging static property.")]
public bool ApplyDebugging
{
get => Settings.EnableDebugging;
set => Settings.EnableDebugging = value;
}
public bool ApplyCaching { get; set; } = !System.Diagnostics.Debugger.IsAttached;
public bool ApplyDebugging { get; set; } = System.Diagnostics.Debugger.IsAttached;
public bool ApplyInspection { get; set; } = System.Diagnostics.Debugger.IsAttached;
public static DocumentMetadata Default => new DocumentMetadata();
}
@@ -4,11 +4,6 @@ namespace QuestPDF.Drawing.Exceptions
{
public class DocumentDrawingException : Exception
{
internal DocumentDrawingException(string message) : base(message)
{
}
internal DocumentDrawingException(string message, Exception inner) : base(message, inner)
{
@@ -15,21 +15,21 @@ namespace QuestPDF.Drawing.Exceptions
return $"Cannot create the {documentType} document using the {libraryName} library. " +
$"This exception usually means that, on your operating system where you run the application, {libraryName} requires installing additional dependencies. " +
$"Such dependencies are available as additional nuget packages, for example {nugetConvention}.Linux.NoDependencies. " +
$"Some operating systems may require installing multiple nugets, e.g. MacOS may need both {nugetConvention}.macOS.NoDependencies and {nugetConvention}.Linux.NoDependencies." +
$"Such dependencies are available as additional nuget packages, for example {nugetConvention}.Linux. " +
$"Some operating systems may require installing multiple nugets, e.g. MacOS may need both {nugetConvention}.macOS and {nugetConvention}.Linux." +
$"Please refer to the {libraryName} documentation for more details. " +
$"Also, please consult the inner exception that has been originally thrown by the dependency library.";
(string GetLibraryName, string nugetConvention) GetLibraryName()
{
if (innerExceptionMessage.Contains("libSkiaSharp"))
return ("SkiaSharp", "SkiaSharp.NativeAssets");
return ("SkiaSharp", "SkiaSharp.NativeAssets.Linux");
if (innerExceptionMessage.Contains("libHarfBuzzSharp"))
return ("HarfBuzzSharp", "HarfBuzzSharp.NativeAssets");
// default
return ("SkiaSharp-related", "*.NativeAssets");
return ("SkiaSharp-related", "*.NativeAssets.Linux");
}
}
}
+16 -63
View File
@@ -1,9 +1,7 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using HarfBuzzSharp;
using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
@@ -14,19 +12,14 @@ namespace QuestPDF.Drawing
{
public static class FontManager
{
private static readonly ConcurrentDictionary<string, FontStyleSet> StyleSets = new();
private static readonly ConcurrentDictionary<TextStyle, SKFontMetrics> FontMetrics = new();
private static readonly ConcurrentDictionary<TextStyle, SKPaint> FontPaints = new();
private static readonly ConcurrentDictionary<string, SKPaint> ColorPaints = new();
private static readonly ConcurrentDictionary<TextStyle, Font> ShaperFonts = new();
private static readonly ConcurrentDictionary<TextStyle, SKFont> Fonts = new();
private static readonly ConcurrentDictionary<TextStyle, TextShaper> TextShapers = new();
private static ConcurrentDictionary<string, FontStyleSet> StyleSets = new();
private static ConcurrentDictionary<object, SKFontMetrics> FontMetrics = new();
private static ConcurrentDictionary<object, SKPaint> FontPaints = new();
private static ConcurrentDictionary<string, SKPaint> ColorPaints = new();
private static ConcurrentDictionary<object, Font> ShaperFonts = new();
private static ConcurrentDictionary<object, SKFont> Fonts = new();
private static ConcurrentDictionary<object, TextShaper> TextShapers = new();
static FontManager()
{
RegisterLibraryDefaultFonts();
}
private static void RegisterFontType(SKData fontData, string? customName = null)
{
foreach (var index in Enumerable.Range(0, 256))
@@ -43,13 +36,8 @@ namespace QuestPDF.Drawing
}
}
[Obsolete("Since version 2022.8 this method has been renamed. Please use the RegisterFontWithCustomName method.")]
[Obsolete("Since version 2022.3, the FontManager class offers better font type matching support. Please use the RegisterFont(Stream stream) method.")]
public static void RegisterFontType(string fontName, Stream stream)
{
RegisterFontWithCustomName(fontName, stream);
}
public static void RegisterFontWithCustomName(string fontName, Stream stream)
{
using var fontData = SKData.Create(stream);
RegisterFontType(fontData);
@@ -61,38 +49,6 @@ namespace QuestPDF.Drawing
using var fontData = SKData.Create(stream);
RegisterFontType(fontData);
}
public static void RegisterFontFromEmbeddedResource(string pathName)
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(pathName);
RegisterFont(stream);
}
private static void RegisterLibraryDefaultFonts()
{
var fontFileNames = new[]
{
"Lato-Black.ttf",
"Lato-BlackItalic.ttf",
"Lato-Bold.ttf",
"Lato-BoldItalic.ttf",
"Lato-Regular.ttf",
"Lato-Italic.ttf",
"Lato-Light.ttf",
"Lato-LightItalic.ttf",
"Lato-Thin.ttf",
"Lato-ThinItalic.ttf"
};
fontFileNames
.Select(x => $"QuestPDF.Resources.DefaultFont.{x}")
.ToList()
.ForEach(RegisterFontFromEmbeddedResource);
}
internal static SKPaint ColorToPaint(this string color)
{
@@ -110,7 +66,7 @@ namespace QuestPDF.Drawing
internal static SKPaint ToPaint(this TextStyle style)
{
return FontPaints.GetOrAdd(style, Convert);
return FontPaints.GetOrAdd(style.PaintKey, key => Convert(style));
static SKPaint Convert(TextStyle style)
{
@@ -147,15 +103,12 @@ namespace QuestPDF.Drawing
if (fontFromDefaultSource != null)
return fontFromDefaultSource;
var availableFontNames = string.Join(", ", SKFontManager.Default.GetFontFamilies());
throw new ArgumentException(
$"The typeface '{style.FontFamily}' could not be found. " +
$"Please consider the following options: " +
$"1) install the font on your operating system or execution environment. " +
$"2) load a font file specifically for QuestPDF usage via the QuestPDF.Drawing.FontManager.RegisterFontType(Stream fileContentStream) static method. " +
$"Available font family names: [{availableFontNames}]");
$"2) load a font file specifically for QuestPDF usage via the QuestPDF.Drawing.FontManager.RegisterFontType(Stream fileContentStream) static method.");
}
static float GetTextScale(TextStyle style)
@@ -172,14 +125,14 @@ namespace QuestPDF.Drawing
internal static SKFontMetrics ToFontMetrics(this TextStyle style)
{
return FontMetrics.GetOrAdd(style, key => key.NormalPosition().ToPaint().FontMetrics);
return FontMetrics.GetOrAdd(style.FontMetricsKey, key => style.NormalPosition().ToPaint().FontMetrics);
}
internal static Font ToShaperFont(this TextStyle style)
{
return ShaperFonts.GetOrAdd(style, key =>
return ShaperFonts.GetOrAdd(style.PaintKey, _ =>
{
var typeface = key.ToPaint().Typeface;
var typeface = style.ToPaint().Typeface;
using var harfBuzzBlob = typeface.OpenStream(out var ttcIndex).ToHarfBuzzBlob();
@@ -200,12 +153,12 @@ namespace QuestPDF.Drawing
internal static TextShaper ToTextShaper(this TextStyle style)
{
return TextShapers.GetOrAdd(style, key => new TextShaper(key));
return TextShapers.GetOrAdd(style.PaintKey, _ => new TextShaper(style));
}
internal static SKFont ToFont(this TextStyle style)
internal static SKFont FoFont(this TextStyle style)
{
return Fonts.GetOrAdd(style, key => key.ToPaint().ToFont());
return Fonts.GetOrAdd(style.PaintKey, _ => style.ToPaint().ToFont());
}
}
}
+25 -25
View File
@@ -94,36 +94,36 @@ namespace QuestPDF.Drawing.Proxy
item.Stack.ToList().ForEach(Traverse);
nestingLevel--;
}
static IEnumerable<string> GetElementConfiguration(IElement element)
{
if (element is DebugPointer)
return Enumerable.Empty<string>();
}
internal static IEnumerable<string> GetElementConfiguration(IElement element)
{
if (element is DebugPointer)
return Enumerable.Empty<string>();
return element
.GetType()
.GetProperties()
.Select(x => new
{
Property = x.Name.PrettifyName(),
Value = x.GetValue(element)
})
.Where(x => !(x.Value is IElement))
.Where(x => x.Value is string || !(x.Value is IEnumerable))
.Where(x => !(x.Value is TextStyle))
.Select(x => $"{x.Property}: {FormatValue(x.Value)}");
string FormatValue(object value)
return element
.GetType()
.GetProperties()
.Select(x => new
{
const int maxLength = 100;
Property = x.Name.PrettifyName(),
Value = x.GetValue(element)
})
.Where(x => !(x.Value is IElement))
.Where(x => x.Value is string || !(x.Value is IEnumerable))
.Where(x => !(x.Value is TextStyle))
.Select(x => $"{x.Property}: {FormatValue(x.Value)}");
string FormatValue(object value)
{
const int maxLength = 100;
var text = value?.ToString() ?? "-";
var text = value?.ToString() ?? "-";
if (text.Length < maxLength)
return text;
if (text.Length < maxLength)
return text;
return text.AsSpan(0, maxLength).ToString() + "...";
}
return text.AsSpan(0, maxLength).ToString() + "...";
}
}
}
+35
View File
@@ -0,0 +1,35 @@
using System.Collections;
using System.Collections.Generic;
using QuestPDF.Infrastructure;
namespace QuestPDF.Drawing.Proxy
{
internal class InspectionProxy : ElementProxy
{
public Dictionary<int, InspectionStateItem> Statistics { get; set; } = new();
public InspectionProxy(Element child)
{
Child = child;
}
internal override void Draw(Size availableSpace)
{
if (Canvas is SkiaCanvasBase canvas)
{
var matrix = canvas.Canvas.TotalMatrix;
var inspectionItem = new InspectionStateItem
{
Element = Child,
Position = new Position(matrix.TransX, matrix.TransY),
Size = availableSpace
};
Statistics[PageContext.CurrentPage] = inspectionItem;
}
base.Draw(availableSpace);
}
}
}
@@ -0,0 +1,7 @@
namespace QuestPDF.Drawing.Proxy
{
public class InspectionState
{
}
}
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using QuestPDF.Infrastructure;
namespace QuestPDF.Drawing.Proxy
{
internal class InspectionStateItem
{
public Element Element { get; internal set; }
public Size Size { get; internal set; }
public Position Position { get; internal set; }
}
internal class InspectionElementLocation
{
public int PageNumber { get; internal set; }
public float Top { get; set; }
public float Left { get; set; }
public float Width { get; set; }
public float Height { get; set; }
}
internal class InspectionElement
{
public string Element { get; internal set; }
public ICollection<InspectionElementLocation> Location { get; internal set; }
public Dictionary<string, string> Properties { get; internal set; }
public ICollection<InspectionElement> Children { get; set; }
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace QuestPDF.Drawing
{
internal struct TextMeasurement
{
public int LineIndex { get; set; }
public float FragmentWidth { get; set; }
}
}
+27 -84
View File
@@ -1,5 +1,4 @@
using System;
using System.Linq;
using HarfBuzzSharp;
using QuestPDF.Infrastructure;
using SkiaSharp;
@@ -10,32 +9,24 @@ namespace QuestPDF.Drawing
internal class TextShaper
{
public const int FontShapingScale = 512;
private Font Font { get; }
private SKPaint Paint { get; }
private TextStyle TextStyle { get; }
private SKFont Font => TextStyle.ToFont();
private Font ShaperFont => TextStyle.ToShaperFont();
private SKPaint Paint => TextStyle.ToPaint();
public TextShaper(TextStyle textStyle)
public TextShaper(TextStyle style)
{
TextStyle = textStyle;
Font = style.ToShaperFont();
Paint = style.ToPaint();
}
public TextShapingResult Shape(string text)
{
using var buffer = new Buffer();
var buffer = new Buffer();
PopulateBufferWithText(buffer, text);
buffer.GuessSegmentProperties();
if (TextStyle.Direction == TextDirection.LeftToRight)
buffer.Direction = Direction.LeftToRight;
if (TextStyle.Direction == TextDirection.RightToLeft)
buffer.Direction = Direction.RightToLeft;
ShaperFont.Shape(buffer);
Font.Shape(buffer);
var length = buffer.Length;
var glyphInfos = buffer.GlyphInfos;
@@ -62,7 +53,7 @@ namespace QuestPDF.Drawing
yOffset += glyphPositions[i].YAdvance * scaleY;
}
return new TextShapingResult(buffer.Direction, glyphs);
return new TextShapingResult(glyphs);
}
void PopulateBufferWithText(Buffer buffer, string text)
@@ -98,65 +89,29 @@ namespace QuestPDF.Drawing
internal class TextShapingResult
{
private Direction Direction { get; }
private ShapedGlyph[] Glyphs { get; }
public ShapedGlyph[] Glyphs { get; }
public int Length => Glyphs.Length;
public ShapedGlyph this[int index] =>
Direction == Direction.LeftToRight
? Glyphs[index]
: Glyphs[Glyphs.Length - 1 - index];
public TextShapingResult(Direction direction, ShapedGlyph[] glyphs)
public TextShapingResult(ShapedGlyph[] glyphs)
{
Direction = direction;
Glyphs = glyphs;
}
public int BreakText(int startIndex, float maxWidth)
{
return Direction switch
var index = startIndex;
maxWidth += Glyphs[startIndex].Position.X;
while (index < Glyphs.Length)
{
Direction.LeftToRight => BreakTextLeftToRight(),
Direction.RightToLeft => BreakTextRightToLeft(),
_ => throw new ArgumentOutOfRangeException()
};
int BreakTextLeftToRight()
{
var index = startIndex;
maxWidth += Glyphs[startIndex].Position.X;
while (index < Glyphs.Length)
{
var glyph = Glyphs[index];
var glyph = Glyphs[index];
if (glyph.Position.X + glyph.Width > maxWidth + Size.Epsilon)
break;
if (glyph.Position.X + glyph.Width > maxWidth + Size.Epsilon)
break;
index++;
}
return index - 1;
index++;
}
int BreakTextRightToLeft()
{
var index = startIndex;
var startOffset = this[startIndex].Position.X + this[startIndex].Width;
while (index < Glyphs.Length)
{
if (startOffset - this[index].Position.X > maxWidth + Size.Epsilon)
break;
index++;
}
return index - 1;
}
return index - 1;
}
public float MeasureWidth(int startIndex, int endIndex)
@@ -164,28 +119,20 @@ namespace QuestPDF.Drawing
if (Glyphs.Length == 0)
return 0;
var start = this[startIndex];
var end = this[endIndex];
var start = Glyphs[startIndex];
var end = Glyphs[endIndex];
return Direction switch
{
Direction.LeftToRight => end.Position.X - start.Position.X + end.Width,
Direction.RightToLeft => start.Position.X - end.Position.X + start.Width,
_ => throw new NotSupportedException()
};
return end.Position.X - start.Position.X + end.Width;
}
public DrawTextCommand? PositionText(int startIndex, int endIndex, TextStyle textStyle)
{
if (Glyphs.Length == 0)
return null;
if (startIndex > endIndex)
return null;
using var skTextBlobBuilder = new SKTextBlobBuilder();
var positionedRunBuffer = skTextBlobBuilder.AllocatePositionedRun(textStyle.ToFont(), endIndex - startIndex + 1);
var positionedRunBuffer = skTextBlobBuilder.AllocatePositionedRun(textStyle.FoFont(), endIndex - startIndex + 1);
var glyphSpan = positionedRunBuffer.GetGlyphSpan();
var positionSpan = positionedRunBuffer.GetPositionSpan();
@@ -193,18 +140,14 @@ namespace QuestPDF.Drawing
{
var runIndex = sourceIndex - startIndex;
glyphSpan[runIndex] = this[sourceIndex].Codepoint;
positionSpan[runIndex] = this[sourceIndex].Position;
glyphSpan[runIndex] = Glyphs[sourceIndex].Codepoint;
positionSpan[runIndex] = Glyphs[sourceIndex].Position;
}
var firstVisualCharacterIndex = Direction == Direction.LeftToRight
? startIndex
: endIndex;
return new DrawTextCommand
{
SkTextBlob = skTextBlobBuilder.Build(),
TextOffsetX = -this[firstVisualCharacterIndex].Position.X
TextOffsetX = -Glyphs[startIndex].Position.X
};
}
}
+1 -10
View File
@@ -4,10 +4,8 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class AspectRatio : ContainerElement, ICacheable, IContentDirectionAware
internal class AspectRatio : ContainerElement, ICacheable
{
public ContentDirection ContentDirection { get; set; }
public float Ratio { get; set; } = 1;
public AspectRatioOption Option { get; set; } = AspectRatioOption.FitWidth;
@@ -44,14 +42,7 @@ namespace QuestPDF.Elements
return;
var size = GetTargetSize(availableSpace);
var offset = ContentDirection == ContentDirection.LeftToRight
? Position.Zero
: new Position(availableSpace.Width - size.Width, 0);
Canvas.Translate(offset);
base.Draw(size);
Canvas.Translate(offset.Reverse());
}
private Size GetTargetSize(Size availableSpace)
+1 -4
View File
@@ -1,5 +1,4 @@
using QuestPDF.Drawing;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SkiaSharp;
@@ -13,9 +12,7 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
return availableSpace.IsNegative()
? SpacePlan.Wrap()
: SpacePlan.FullRender(availableSpace);
return SpacePlan.FullRender(availableSpace);
}
internal override void Draw(Size availableSpace)
+2 -7
View File
@@ -74,7 +74,7 @@ namespace QuestPDF.Elements
command.ColumnItem.IsRendered = true;
var targetSize = new Size(availableSpace.Width, command.Size.Height);
Canvas.Translate(command.Offset);
command.ColumnItem.Draw(targetSize);
Canvas.Translate(command.Offset.Reverse());
@@ -94,12 +94,7 @@ namespace QuestPDF.Elements
if (item.IsRendered)
continue;
var availableHeight = availableSpace.Height - topOffset;
if (availableHeight < 0)
break;
var itemSpace = new Size(availableSpace.Width, availableHeight);
var itemSpace = new Size(availableSpace.Width, availableSpace.Height - topOffset);
var measurement = item.Measure(itemSpace);
if (measurement.Type == SpacePlanType.Wrap)
+3 -11
View File
@@ -5,10 +5,8 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class Constrained : ContainerElement, ICacheable, IContentDirectionAware
internal class Constrained : ContainerElement, ICacheable
{
public ContentDirection ContentDirection { get; set; }
public float? MinWidth { get; set; }
public float? MaxWidth { get; set; }
@@ -47,17 +45,11 @@ namespace QuestPDF.Elements
internal override void Draw(Size availableSpace)
{
var size = new Size(
var available = new Size(
Min(MaxWidth, availableSpace.Width),
Min(MaxHeight, availableSpace.Height));
var offset = ContentDirection == ContentDirection.LeftToRight
? Position.Zero
: new Position(availableSpace.Width - size.Width, 0);
Canvas.Translate(offset);
base.Draw(size);
Canvas.Translate(offset.Reverse());
Child?.Draw(available);
}
private static float Min(float? x, float y)
@@ -1,9 +0,0 @@
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class ContentDirectionSetter : ContainerElement
{
public ContentDirection ContentDirection { get; set; }
}
}
+3 -9
View File
@@ -14,10 +14,8 @@ namespace QuestPDF.Elements
public Position Offset { get; set; }
}
internal class Decoration : Element, ICacheable, IContentDirectionAware
internal class Decoration : Element, ICacheable
{
public ContentDirection ContentDirection { get; set; }
internal Element Before { get; set; } = new Empty();
internal Element Content { get; set; } = new Empty();
internal Element After { get; set; } = new Empty();
@@ -66,13 +64,9 @@ namespace QuestPDF.Elements
{
var elementSize = new Size(width, command.Measurement.Height);
var offset = ContentDirection == ContentDirection.LeftToRight
? command.Offset
: new Position(availableSpace.Width - width, command.Offset.Y);
Canvas.Translate(offset);
Canvas.Translate(command.Offset);
command.Element.Draw(elementSize);
Canvas.Translate(offset.Reverse());
Canvas.Translate(command.Offset.Reverse());
}
}
+8 -15
View File
@@ -6,14 +6,13 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class DynamicHost : Element, IStateResettable, IContentDirectionAware
internal class DynamicHost : Element, IStateResettable
{
private DynamicComponentProxy Child { get; }
private object InitialComponentState { get; set; }
internal TextStyle TextStyle { get; set; } = TextStyle.Default;
public ContentDirection ContentDirection { get; set; }
internal TextStyle TextStyle { get; } = new();
public DynamicHost(DynamicComponentProxy child)
{
Child = child;
@@ -52,14 +51,12 @@ namespace QuestPDF.Elements
var context = new DynamicContext
{
PageContext = PageContext,
Canvas = Canvas,
TextStyle = TextStyle,
ContentDirection = ContentDirection,
PageNumber = PageContext.CurrentPage,
TotalPages = PageContext.GetLocation(Infrastructure.PageContext.DocumentLocation).PageEnd,
PageContext = PageContext,
Canvas = Canvas,
TextStyle = TextStyle,
AvailableSize = availableSize
};
@@ -76,9 +73,7 @@ namespace QuestPDF.Elements
{
internal IPageContext PageContext { get; set; }
internal ICanvas Canvas { get; set; }
internal TextStyle TextStyle { get; set; }
internal ContentDirection ContentDirection { get; set; }
public int PageNumber { get; internal set; }
public int TotalPages { get; internal set; }
@@ -90,9 +85,7 @@ namespace QuestPDF.Elements
content(container);
container.ApplyDefaultTextStyle(TextStyle);
container.ApplyContentDirection(ContentDirection);
container.InjectDependencies(PageContext, Canvas);
container.VisitChildren(x => x?.Initialize(PageContext, Canvas));
container.VisitChildren(x => (x as IStateResettable)?.ResetState());
container.Size = container.Measure(Size.Max);
+8 -6
View File
@@ -1,6 +1,5 @@
using System;
using QuestPDF.Drawing;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SkiaSharp;
@@ -12,9 +11,7 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
return availableSpace.IsNegative()
? SpacePlan.Wrap()
: SpacePlan.FullRender(availableSpace);
return SpacePlan.FullRender(availableSpace.Width, availableSpace.Height);
}
internal override void Draw(Size availableSpace)
@@ -24,8 +21,13 @@ namespace QuestPDF.Elements
if (imageData == null)
return;
using var image = SKImage.FromEncodedData(imageData);
Canvas.DrawImage(image, Position.Zero, availableSpace);
var imageElement = new Image
{
InternalImage = SKImage.FromEncodedData(imageData)
};
imageElement.Initialize(PageContext, Canvas);
imageElement.Draw(availableSpace);
}
}
}
+1 -4
View File
@@ -1,5 +1,4 @@
using QuestPDF.Drawing;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
@@ -10,9 +9,7 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
return availableSpace.IsNegative()
? SpacePlan.Wrap()
: SpacePlan.FullRender(0, 0);
return SpacePlan.FullRender(0, 0);
}
internal override void Draw(Size availableSpace)
+1 -4
View File
@@ -1,5 +1,4 @@
using QuestPDF.Drawing;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using SkiaSharp;
@@ -16,9 +15,7 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
return availableSpace.IsNegative()
? SpacePlan.Wrap()
: SpacePlan.FullRender(availableSpace);
return SpacePlan.FullRender(availableSpace);
}
internal override void Draw(Size availableSpace)
+42 -58
View File
@@ -19,24 +19,16 @@ namespace QuestPDF.Elements
Justify,
SpaceAround
}
internal struct InlinedMeasurement
{
public Element Element { get; set; }
public SpacePlan Size { get; set; }
}
internal class Inlined : Element, IStateResettable, IContentDirectionAware
internal class Inlined : Element, IStateResettable
{
public ContentDirection ContentDirection { get; set; }
public List<InlinedElement> Elements { get; internal set; } = new List<InlinedElement>();
private Queue<InlinedElement> ChildrenQueue { get; set; }
internal float VerticalSpacing { get; set; }
internal float HorizontalSpacing { get; set; }
internal InlinedAlignment? ElementsAlignment { get; set; }
internal InlinedAlignment ElementsAlignment { get; set; }
internal VerticalAlignment BaselineAlignment { get; set; }
public void ResetState()
@@ -51,8 +43,6 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
SetDefaultAlignment();
if (!ChildrenQueue.Any())
return SpacePlan.FullRender(Size.Zero);
@@ -85,14 +75,15 @@ namespace QuestPDF.Elements
internal override void Draw(Size availableSpace)
{
SetDefaultAlignment();
var lines = Compose(availableSpace);
var topOffset = 0f;
foreach (var line in lines)
{
var height = line.Max(x => x.Size.Height);
var height = line
.Select(x => x.Measure(Size.Max))
.Where(x => x.Type != SpacePlanType.Wrap)
.Max(x => x.Height);
DrawLine(line);
@@ -103,58 +94,58 @@ namespace QuestPDF.Elements
Canvas.Translate(new Position(0, -topOffset));
lines.SelectMany(x => x).ToList().ForEach(x => ChildrenQueue.Dequeue());
void DrawLine(ICollection<InlinedMeasurement> lineMeasurements)
void DrawLine(ICollection<InlinedElement> elements)
{
var lineSize = GetLineSize(lineMeasurements);
var lineSize = GetLineSize(elements);
var elementOffset = ElementOffset();
var leftOffset = AlignOffset();
Canvas.Translate(new Position(leftOffset, 0));
foreach (var measurement in lineMeasurements)
foreach (var element in elements)
{
var size = (Size)measurement.Size;
var size = (Size)element.Measure(Size.Max);
var baselineOffset = BaselineOffset(size, lineSize.Height);
if (size.Height == 0)
size = new Size(size.Width, lineSize.Height);
var offset = ContentDirection == ContentDirection.LeftToRight
? new Position(leftOffset, baselineOffset)
: new Position(availableSpace.Width - size.Width - leftOffset, baselineOffset);
Canvas.Translate(offset);
measurement.Element.Draw(size);
Canvas.Translate(offset.Reverse());
Canvas.Translate(new Position(0, baselineOffset));
element.Draw(size);
Canvas.Translate(new Position(0, -baselineOffset));
leftOffset += size.Width + elementOffset;
Canvas.Translate(new Position(size.Width + elementOffset, 0));
}
Canvas.Translate(new Position(-leftOffset, 0));
float ElementOffset()
{
var difference = availableSpace.Width - lineSize.Width;
if (lineMeasurements.Count == 1)
if (elements.Count == 1)
return 0;
return ElementsAlignment switch
{
InlinedAlignment.Justify => difference / (lineMeasurements.Count - 1),
InlinedAlignment.SpaceAround => difference / (lineMeasurements.Count + 1),
InlinedAlignment.Justify => difference / (elements.Count - 1),
InlinedAlignment.SpaceAround => difference / (elements.Count + 1),
_ => HorizontalSpacing
};
}
float AlignOffset()
{
var emptySpace = availableSpace.Width - lineSize.Width - (lineMeasurements.Count - 1) * HorizontalSpacing;
var difference = availableSpace.Width - lineSize.Width - (elements.Count - 1) * HorizontalSpacing;
return ElementsAlignment switch
{
InlinedAlignment.Left => ContentDirection == ContentDirection.LeftToRight ? 0 : emptySpace,
InlinedAlignment.Left => 0,
InlinedAlignment.Justify => 0,
InlinedAlignment.SpaceAround => elementOffset,
InlinedAlignment.Center => emptySpace / 2,
InlinedAlignment.Right => ContentDirection == ContentDirection.LeftToRight ? emptySpace : 0,
InlinedAlignment.Center => difference / 2,
InlinedAlignment.Right => difference,
_ => 0
};
}
@@ -173,29 +164,24 @@ namespace QuestPDF.Elements
}
}
void SetDefaultAlignment()
Size GetLineSize(ICollection<InlinedElement> elements)
{
if (ElementsAlignment.HasValue)
return;
ElementsAlignment = ContentDirection == ContentDirection.LeftToRight
? InlinedAlignment.Left
: InlinedAlignment.Right;
}
Size GetLineSize(ICollection<InlinedMeasurement> measurements)
{
var width = measurements.Sum(x => x.Size.Width);
var height = measurements.Max(x => x.Size.Height);
var sizes = elements
.Select(x => x.Measure(Size.Max))
.Where(x => x.Type != SpacePlanType.Wrap)
.ToList();
var width = sizes.Sum(x => x.Width);
var height = sizes.Max(x => x.Height);
return new Size(width, height);
}
// list of lines, each line is a list of elements
private ICollection<ICollection<InlinedMeasurement>> Compose(Size availableSize)
private ICollection<ICollection<InlinedElement>> Compose(Size availableSize)
{
var queue = new Queue<InlinedElement>(ChildrenQueue);
var result = new List<ICollection<InlinedMeasurement>>();
var result = new List<ICollection<InlinedElement>>();
var topOffset = 0f;
@@ -206,7 +192,10 @@ namespace QuestPDF.Elements
if (!line.Any())
break;
var height = line.Max(x => x.Size.Height);
var height = line
.Select(x => x.Measure(availableSize))
.Where(x => x.Type != SpacePlanType.Wrap)
.Max(x => x.Height);
if (topOffset + height > availableSize.Height + Size.Epsilon)
break;
@@ -217,9 +206,9 @@ namespace QuestPDF.Elements
return result;
ICollection<InlinedMeasurement> GetNextLine()
ICollection<InlinedElement> GetNextLine()
{
var result = new List<InlinedMeasurement>();
var result = new List<InlinedElement>();
var leftOffset = GetInitialAlignmentOffset();
while (true)
@@ -228,7 +217,7 @@ namespace QuestPDF.Elements
break;
var element = queue.Peek();
var size = element.Measure(new Size(availableSize.Width, Size.Max.Height));
var size = element.Measure(Size.Max);
if (size.Type == SpacePlanType.Wrap)
break;
@@ -238,12 +227,7 @@ namespace QuestPDF.Elements
queue.Dequeue();
leftOffset += size.Width + HorizontalSpacing;
result.Add(new InlinedMeasurement
{
Element = element,
Size = size
});
result.Add(element);
}
return result;
+1 -1
View File
@@ -19,7 +19,7 @@ namespace QuestPDF.Elements
{
return Children;
}
internal override SpacePlan Measure(Size availableSpace)
{
return Children
-3
View File
@@ -23,9 +23,6 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
if (availableSpace.IsNegative())
return SpacePlan.Wrap();
return Type switch
{
LineType.Vertical when availableSpace.Width + Infrastructure.Size.Epsilon >= Size => SpacePlan.FullRender(Size, 0),
+1 -9
View File
@@ -3,10 +3,8 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class MinimalBox : ContainerElement, IContentDirectionAware
internal class MinimalBox : ContainerElement
{
public ContentDirection ContentDirection { get; set; }
internal override void Draw(Size availableSpace)
{
var targetSize = base.Measure(availableSpace);
@@ -14,13 +12,7 @@ namespace QuestPDF.Elements
if (targetSize.Type == SpacePlanType.Wrap)
return;
var translate = ContentDirection == ContentDirection.RightToLeft
? new Position(availableSpace.Width - targetSize.Width, 0)
: Position.Zero;
Canvas.Translate(translate);
base.Draw(targetSize);
Canvas.Translate(translate.Reverse());
}
}
}
+3 -3
View File
@@ -8,8 +8,7 @@ namespace QuestPDF.Elements
{
internal class Page : IComponent
{
public ContentDirection ContentDirection { get; set; }
public TextStyle DefaultTextStyle { get; set; } = TextStyle.Default;
public TextStyle DefaultTextStyle { get; set; } = new TextStyle();
public Size MinSize { get; set; } = PageSizes.A4;
public Size MaxSize { get; set; } = PageSizes.A4;
@@ -31,7 +30,7 @@ namespace QuestPDF.Elements
public void Compose(IContainer container)
{
container
.ContentDirection(ContentDirection)
.Container()
.Background(BackgroundColor)
.Layers(layers =>
{
@@ -42,6 +41,7 @@ namespace QuestPDF.Elements
layers
.PrimaryLayer()
.DebugPointer("Page content")
.MinWidth(MinSize.Width)
.MinHeight(MinSize.Height)
-4
View File
@@ -1,5 +1,4 @@
using QuestPDF.Drawing;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
@@ -15,9 +14,6 @@ namespace QuestPDF.Elements
internal override SpacePlan Measure(Size availableSpace)
{
if (availableSpace.IsNegative())
return SpacePlan.Wrap();
if (IsRendered)
return SpacePlan.FullRender(0, 0);
-1
View File
@@ -25,7 +25,6 @@ namespace QuestPDF.Elements
{
if (string.IsNullOrWhiteSpace(Text))
x.MaxHeight(32).Image(ImageData, ImageScaling.FitArea);
else
x.Text(Text).FontSize(14);
});
+3 -14
View File
@@ -31,10 +31,8 @@ namespace QuestPDF.Elements
public Position Offset { get; set; }
}
internal class Row : Element, ICacheable, IStateResettable, IContentDirectionAware
internal class Row : Element, ICacheable, IStateResettable
{
public ContentDirection ContentDirection { get; set; }
internal List<RowItem> Items { get; } = new();
internal float Spacing { get; set; }
@@ -48,11 +46,6 @@ namespace QuestPDF.Elements
return Items;
}
internal override void CreateProxy(Func<Element?, Element?> create)
{
Items.ForEach(x => x.Child = create(x.Child));
}
internal override SpacePlan Measure(Size availableSpace)
{
if (!Items.Any())
@@ -93,13 +86,9 @@ namespace QuestPDF.Elements
if (command.Measurement.Type == SpacePlanType.Wrap)
continue;
var offset = ContentDirection == ContentDirection.LeftToRight
? command.Offset
: new Position(availableSpace.Width - command.Offset.X - command.Size.Width, 0);
Canvas.Translate(offset);
Canvas.Translate(command.Offset);
command.RowItem.Draw(command.Size);
Canvas.Translate(offset.Reverse());
Canvas.Translate(command.Offset.Reverse());
}
if (Items.All(x => x.IsRendered))
+21 -38
View File
@@ -9,15 +9,12 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements.Table
{
internal class Table : Element, IStateResettable, IContentDirectionAware
internal class Table : Element, IStateResettable
{
public ContentDirection ContentDirection { get; set; }
public List<TableColumnDefinition> Columns { get; set; } = new();
public List<TableCell> Cells { get; set; } = new();
public List<TableColumnDefinition> Columns { get; set; } = new List<TableColumnDefinition>();
public List<TableCell> Cells { get; set; } = new List<TableCell>();
public bool ExtendLastCellsToTableBottom { get; set; }
private bool CacheInitialized { get; set; }
private int StartingRowsCount { get; set; }
private int RowsCount { get; set; }
private int CurrentRow { get; set; }
@@ -27,8 +24,17 @@ namespace QuestPDF.Elements.Table
// inner table: list of all cells that ends at the corresponding row
private TableCell[][] CellsCache { get; set; }
private int MaxRow { get; set; }
private int MaxRowSpan { get; set; }
internal override void Initialize(IPageContext pageContext, ICanvas canvas)
{
StartingRowsCount = Cells.Select(x => x.Row).DefaultIfEmpty(0).Max();
RowsCount = Cells.Select(x => x.Row + x.RowSpan - 1).DefaultIfEmpty(0).Max();
Cells = Cells.OrderBy(x => x.Row).ThenBy(x => x.Column).ToList();
BuildCache();
base.Initialize(pageContext, canvas);
}
internal override IEnumerable<Element?> GetChildren()
{
return Cells;
@@ -36,26 +42,9 @@ namespace QuestPDF.Elements.Table
public void ResetState()
{
Initialize();
foreach (var x in Cells)
x.IsRendered = false;
Cells.ForEach(x => x.IsRendered = false);
CurrentRow = 1;
}
private void Initialize()
{
if (CacheInitialized)
return;
StartingRowsCount = Cells.Select(x => x.Row).DefaultIfEmpty(0).Max();
RowsCount = Cells.Select(x => x.Row + x.RowSpan - 1).DefaultIfEmpty(0).Max();
Cells = Cells.OrderBy(x => x.Row).ThenBy(x => x.Column).ToList();
BuildCache();
CacheInitialized = true;
}
private void BuildCache()
{
@@ -65,7 +54,6 @@ namespace QuestPDF.Elements.Table
if (Cells.Count == 0)
{
MaxRow = 0;
MaxRowSpan = 1;
CellsCache = Array.Empty<TableCell[]>();
return;
@@ -76,7 +64,6 @@ namespace QuestPDF.Elements.Table
.ToDictionary(x => x.Key, x => x.OrderBy(x => x.Column).ToArray());
MaxRow = groups.Max(x => x.Key);
MaxRowSpan = Cells.Max(x => x.RowSpan);
CellsCache = Enumerable
.Range(0, MaxRow + 1)
@@ -120,13 +107,9 @@ namespace QuestPDF.Elements.Table
if (command.Measurement.Type == SpacePlanType.Wrap)
continue;
var offset = ContentDirection == ContentDirection.LeftToRight
? command.Offset
: new Position(availableSpace.Width - command.Offset.X - command.Size.Width, command.Offset.Y);
Canvas.Translate(offset);
Canvas.Translate(command.Offset);
command.Cell.Draw(command.Size);
Canvas.Translate(offset.Reverse());
Canvas.Translate(command.Offset.Reverse());
}
CurrentRow = FindLastRenderedRow(renderingCommands) + 1;
@@ -173,7 +156,7 @@ namespace QuestPDF.Elements.Table
if (ExtendLastCellsToTableBottom)
AdjustLastCellSizes(tableHeight, commands);
return commands;
static float[] GetColumnLeftOffsets(IList<TableColumnDefinition> columns)
@@ -214,9 +197,9 @@ namespace QuestPDF.Elements.Table
currentRow = cell.Row;
}
// cell visibility optimizations
if (cell.Row > maxRenderingRow + MaxRowSpan)
if (cell.Row > maxRenderingRow)
break;
// calculate cell position / size
@@ -233,14 +216,14 @@ namespace QuestPDF.Elements.Table
{
maxRenderingRow = Math.Min(maxRenderingRow, cell.Row + cell.RowSpan - 1);
}
// corner case: if cell within the row want to wrap to the next page, do not attempt to render this row
if (cellSize.Type == SpacePlanType.Wrap)
{
maxRenderingRow = Math.Min(maxRenderingRow, cell.Row - 1);
continue;
}
// update position of the last row that cell occupies
var bottomRow = cell.Row + cell.RowSpan - 1;
rowBottomOffsets[bottomRow] = Math.Max(rowBottomOffsets[bottomRow], topOffset + cellSize.Height);
-160
View File
@@ -1,160 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using QuestPDF.Drawing;
using QuestPDF.Drawing.Exceptions;
using QuestPDF.Elements.Text.Items;
using QuestPDF.Fluent;
using QuestPDF.Infrastructure;
using SkiaSharp;
namespace QuestPDF.Elements.Text
{
internal static class FontFallback
{
public struct TextRun
{
public string Content { get; set; }
public TextStyle Style { get; set; }
}
public class FallbackOption
{
public TextStyle Style { get; set; }
public SKFont Font { get; set; }
public SKTypeface Typeface { get; set; }
}
private static SKFontManager FontManager => SKFontManager.Default;
public static IEnumerable<TextRun> SplitWithFontFallback(this string text, TextStyle textStyle)
{
var fallbackOptions = GetFallbackOptions(textStyle).ToArray();
var spanStartIndex = 0;
var spanFallbackOption = fallbackOptions[0];
for (var i = 0; i < text.Length; i += char.IsSurrogatePair(text, i) ? 2 : 1)
{
var codepoint = char.ConvertToUtf32(text, i);
var newFallbackOption = MatchFallbackOption(fallbackOptions, codepoint);
if (newFallbackOption == spanFallbackOption)
continue;
yield return new TextRun
{
Content = text.Substring(spanStartIndex, i - spanStartIndex),
Style = spanFallbackOption.Style
};
spanStartIndex = i;
spanFallbackOption = newFallbackOption;
}
if (spanStartIndex > text.Length)
yield break;
yield return new TextRun
{
Content = text.Substring(spanStartIndex, text.Length - spanStartIndex),
Style = spanFallbackOption.Style
};
static IEnumerable<FallbackOption> GetFallbackOptions(TextStyle? textStyle)
{
while (textStyle != null)
{
var font = textStyle.ToFont();
yield return new FallbackOption
{
Style = textStyle,
Font = font,
Typeface = font.Typeface
};
textStyle = textStyle.Fallback;
}
}
static FallbackOption MatchFallbackOption(ICollection<FallbackOption> fallbackOptions, int codepoint)
{
foreach (var fallbackOption in fallbackOptions)
{
if (fallbackOption.Font.ContainsGlyph(codepoint))
return fallbackOption;
}
throw CreateNotMatchingFontException(codepoint);
}
static Exception CreateNotMatchingFontException(int codepoint)
{
var character = char.ConvertFromUtf32(codepoint);
var unicode = $"U-{codepoint:X4}";
var proposedFonts = FindFontsContainingGlyph(codepoint);
var proposedFontsFormatted = proposedFonts.Any() ? string.Join(", ", proposedFonts) : "no fonts available";
return new DocumentDrawingException(
$"Could not find an appropriate font fallback for glyph: {unicode} '{character}'. " +
$"Font families available on current environment that contain this glyph: {proposedFontsFormatted}. " +
$"Possible solutions: " +
$"1) Use one of the listed fonts as the primary font in your document. " +
$"2) Configure the fallback TextStyle using the 'TextStyle.Fallback' method with one of the listed fonts. ");
}
static IEnumerable<string> FindFontsContainingGlyph(int codepoint)
{
var fontManager = SKFontManager.Default;
return fontManager
.GetFontFamilies()
.Select(fontManager.MatchFamily)
.Where(x => x.ContainsGlyph(codepoint))
.Select(x => x.FamilyName);
}
}
public static IEnumerable<ITextBlockItem> ApplyFontFallback(this ICollection<ITextBlockItem> textBlockItems)
{
foreach (var textBlockItem in textBlockItems)
{
if (textBlockItem is TextBlockPageNumber or TextBlockElement)
{
yield return textBlockItem;
}
else if (textBlockItem is TextBlockSpan textBlockSpan)
{
if (!Settings.CheckIfAllTextGlyphsAreAvailable && textBlockSpan.Style.Fallback == null)
{
yield return textBlockSpan;
continue;
}
var textRuns = textBlockSpan.Text.SplitWithFontFallback(textBlockSpan.Style);
foreach (var textRun in textRuns)
{
var newElement = textBlockSpan switch
{
TextBlockHyperlink hyperlink => new TextBlockHyperlink { Url = hyperlink.Url },
TextBlockSectionLink sectionLink => new TextBlockSectionLink { SectionName = sectionLink.SectionName },
TextBlockSpan => new TextBlockSpan()
};
newElement.Text = textRun.Content;
newElement.Style = textRun.Style;
yield return newElement;
}
}
else
{
throw new NotSupportedException();
}
}
}
}
}
@@ -12,7 +12,7 @@ namespace QuestPDF.Elements.Text.Items
public TextMeasurementResult? Measure(TextMeasurementRequest request)
{
Element.VisitChildren(x => (x as IStateResettable)?.ResetState());
Element.InjectDependencies(request.PageContext, request.Canvas);
Element.VisitChildren(x => x.Initialize(request.PageContext, request.Canvas));
var measurement = Element.Measure(new Size(request.AvailableWidth, Size.Max.Height));
@@ -37,7 +37,7 @@ namespace QuestPDF.Elements.Text.Items
public void Draw(TextDrawingRequest request)
{
Element.VisitChildren(x => (x as IStateResettable)?.ResetState());
Element.InjectDependencies(request.PageContext, request.Canvas);
Element.VisitChildren(x => x.Initialize(request.PageContext, request.Canvas));
request.Canvas.Translate(new Position(0, request.TotalAscent));
Element.Draw(new Size(request.TextSize.Width, -request.TotalAscent));
+10 -10
View File
@@ -14,8 +14,8 @@ namespace QuestPDF.Elements.Text.Items
internal class TextBlockSpan : ITextBlockItem
{
public string Text { get; set; }
public TextStyle Style { get; set; } = TextStyle.Default;
private TextShapingResult? TextShapingResult { get; set; }
public TextStyle Style { get; set; } = new();
public TextShapingResult? TextShapingResult { get; set; }
private Dictionary<(int startIndex, float availableWidth), TextMeasurementResult?> MeasureCache = new ();
protected virtual bool EnableTextCache => true;
@@ -47,11 +47,11 @@ namespace QuestPDF.Elements.Text.Items
// ignore leading spaces
if (!request.IsFirstElementInBlock && request.IsFirstElementInLine)
{
while (startIndex < TextShapingResult.Length && Text[startIndex] == spaceCodepoint)
while (startIndex < TextShapingResult.Glyphs.Length && Text[startIndex] == spaceCodepoint)
startIndex++;
}
if (TextShapingResult.Length == 0 || startIndex == TextShapingResult.Length)
if (TextShapingResult.Glyphs.Length == 0 || startIndex == TextShapingResult.Glyphs.Length)
{
return new TextMeasurementResult
{
@@ -66,7 +66,7 @@ namespace QuestPDF.Elements.Text.Items
// start breaking text from requested position
var endIndex = TextShapingResult.BreakText(startIndex, request.AvailableWidth);
if (endIndex < startIndex)
if (endIndex < 0)
return null;
// break text only on spaces
@@ -90,7 +90,7 @@ namespace QuestPDF.Elements.Text.Items
StartIndex = startIndex,
EndIndex = wrappedText.Value.endIndex,
NextIndex = wrappedText.Value.nextIndex,
TotalIndex = TextShapingResult.Length - 1
TotalIndex = TextShapingResult.Glyphs.Length - 1
};
}
@@ -102,7 +102,7 @@ namespace QuestPDF.Elements.Text.Items
// textLength - length of the part of the text that fits in available width (creating a line)
// entire text fits, no need to wrap
if (endIndex == TextShapingResult.Length - 1)
if (endIndex == TextShapingResult.Glyphs.Length - 1)
return (endIndex, endIndex);
// breaking anywhere
@@ -110,7 +110,7 @@ namespace QuestPDF.Elements.Text.Items
return (endIndex, endIndex + 1);
// current line ends at word, next character is space, perfect place to wrap
if (TextShapingResult[endIndex].Codepoint != spaceCodepoint && TextShapingResult[endIndex + 1].Codepoint == spaceCodepoint)
if (TextShapingResult.Glyphs[endIndex].Codepoint != spaceCodepoint && TextShapingResult.Glyphs[endIndex + 1].Codepoint == spaceCodepoint)
return (endIndex, endIndex + 2);
// find last space within the available text to wrap
@@ -118,14 +118,14 @@ namespace QuestPDF.Elements.Text.Items
while (lastSpaceIndex >= startIndex)
{
if (TextShapingResult[lastSpaceIndex].Codepoint == spaceCodepoint)
if (TextShapingResult.Glyphs[lastSpaceIndex].Codepoint == spaceCodepoint)
break;
lastSpaceIndex--;
}
// text contains space that can be used to wrap
if (lastSpaceIndex > 1 && lastSpaceIndex >= startIndex)
if (lastSpaceIndex >= startIndex)
return (lastSpaceIndex - 1, lastSpaceIndex + 1);
// there is no available space to wrap text
+36 -69
View File
@@ -8,65 +8,24 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements.Text
{
internal class TextBlock : Element, IStateResettable, IContentDirectionAware
internal class TextBlock : Element, IStateResettable
{
public ContentDirection ContentDirection { get; set; }
public HorizontalAlignment? Alignment { get; set; }
public HorizontalAlignment Alignment { get; set; } = HorizontalAlignment.Left;
public List<ITextBlockItem> Items { get; set; } = new List<ITextBlockItem>();
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 bool FontFallbackApplied { get; set; } = false;
public void ResetState()
{
ApplyFontFallback();
InitializeQueue();
RenderingQueue = new Queue<ITextBlockItem>(Items);
CurrentElementIndex = 0;
void InitializeQueue()
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (RenderingQueue == null)
{
RenderingQueue = new Queue<ITextBlockItem>(Items);
return;
}
RenderingQueue.Clear();
foreach (var item in Items)
RenderingQueue.Enqueue(item);
}
void ApplyFontFallback()
{
if (FontFallbackApplied)
return;
Items = Items.ApplyFontFallback().ToList();
FontFallbackApplied = true;
}
}
void SetDefaultAlignment()
{
if (Alignment.HasValue)
return;
Alignment = ContentDirection == ContentDirection.LeftToRight
? HorizontalAlignment.Left
: HorizontalAlignment.Right;
}
internal override SpacePlan Measure(Size availableSpace)
{
SetDefaultAlignment();
if (!RenderingQueue.Any())
return SpacePlan.FullRender(Size.Zero);
@@ -94,19 +53,23 @@ namespace QuestPDF.Elements.Text
internal override void Draw(Size availableSpace)
{
SetDefaultAlignment();
var lines = DivideTextItemsIntoLines(availableSpace.Width, availableSpace.Height).ToList();
if (!lines.Any())
return;
var topOffset = 0f;
var heightOffset = 0f;
var widthOffset = 0f;
foreach (var line in lines)
{
var leftOffset = GetAlignmentOffset(line.Width);
widthOffset = 0f;
var alignmentOffset = GetAlignmentOffset(line.Width);
Canvas.Translate(new Position(alignmentOffset, 0));
Canvas.Translate(new Position(0, -line.Ascent));
foreach (var item in line.Elements)
{
var textDrawingRequest = new TextDrawingRequest
@@ -121,20 +84,21 @@ namespace QuestPDF.Elements.Text
TotalAscent = line.Ascent
};
var canvasOffset = ContentDirection == ContentDirection.LeftToRight
? new Position(leftOffset, topOffset - line.Ascent)
: new Position(availableSpace.Width - leftOffset - item.Measurement.Width, topOffset - line.Ascent);
Canvas.Translate(canvasOffset);
item.Item.Draw(textDrawingRequest);
Canvas.Translate(canvasOffset.Reverse());
leftOffset += item.Measurement.Width;
}
topOffset += line.LineHeight;
Canvas.Translate(new Position(item.Measurement.Width, 0));
widthOffset += item.Measurement.Width;
}
Canvas.Translate(new Position(-alignmentOffset, 0));
Canvas.Translate(new Position(-line.Width, line.Ascent));
Canvas.Translate(new Position(0, line.LineHeight));
heightOffset += line.LineHeight;
}
Canvas.Translate(new Position(0, -heightOffset));
lines
.SelectMany(x => x.Elements)
.GroupBy(x => x.Item)
@@ -144,22 +108,25 @@ namespace QuestPDF.Elements.Text
.ForEach(x => RenderingQueue.Dequeue());
var lastElementMeasurement = lines.Last().Elements.Last().Measurement;
CurrentElementIndex = lastElementMeasurement.IsLast ? 0 : lastElementMeasurement.NextIndex;
CurrentElementIndex = lastElementMeasurement.IsLast ? 0 : lastElementMeasurement.EndIndex;
if (!RenderingQueue.Any())
ResetState();
float GetAlignmentOffset(float lineWidth)
{
if (Alignment == HorizontalAlignment.Left)
return 0;
var emptySpace = availableSpace.Width - lineWidth;
return Alignment switch
{
HorizontalAlignment.Left => ContentDirection == ContentDirection.LeftToRight ? 0 : emptySpace,
HorizontalAlignment.Center => emptySpace / 2,
HorizontalAlignment.Right => ContentDirection == ContentDirection.LeftToRight ? emptySpace : 0,
_ => 0
};
if (Alignment == HorizontalAlignment.Right)
return emptySpace;
if (Alignment == HorizontalAlignment.Center)
return emptySpace / 2;
throw new ArgumentException();
}
}
+1 -9
View File
@@ -3,10 +3,8 @@ using QuestPDF.Infrastructure;
namespace QuestPDF.Elements
{
internal class Unconstrained : ContainerElement, IContentDirectionAware, ICacheable
internal class Unconstrained : ContainerElement, ICacheable
{
public ContentDirection ContentDirection { get; set; }
internal override SpacePlan Measure(Size availableSpace)
{
var childSize = base.Measure(Size.Max);
@@ -27,13 +25,7 @@ namespace QuestPDF.Elements
if (measurement.Type == SpacePlanType.Wrap)
return;
var translate = ContentDirection == ContentDirection.RightToLeft
? new Position(-measurement.Width, 0)
: Position.Zero;
Canvas.Translate(translate);
base.Draw(measurement);
Canvas.Translate(translate.Reverse());
}
}
}
+1 -1
View File
@@ -22,7 +22,7 @@ namespace QuestPDF.Fluent
Child = container
});
return container;
return container.DebugPointer("Column Item");;
}
}
@@ -1,26 +0,0 @@
using QuestPDF.Elements;
using QuestPDF.Infrastructure;
namespace QuestPDF.Fluent
{
public static class ContentDirectionExtensions
{
internal static IContainer ContentDirection(this IContainer element, ContentDirection direction)
{
return element.Element(new ContentDirectionSetter
{
ContentDirection = direction
});
}
public static IContainer ContentFromLeftToRight(this IContainer element)
{
return element.ContentDirection(Infrastructure.ContentDirection.LeftToRight);
}
public static IContainer ContentFromRightToLeft(this IContainer element)
{
return element.ContentDirection(Infrastructure.ContentDirection.RightToLeft);
}
}
}
+3 -3
View File
@@ -12,7 +12,7 @@ namespace QuestPDF.Fluent
{
var container = new Container();
Decoration.Before = container;
return container;
return container.DebugPointer("Decoration Before");
}
public void Before(Action<IContainer> handler)
@@ -24,7 +24,7 @@ namespace QuestPDF.Fluent
{
var container = new Container();
Decoration.Content = container;
return container;
return container.DebugPointer("Decoration Content");
}
public void Content(Action<IContainer> handler)
@@ -36,7 +36,7 @@ namespace QuestPDF.Fluent
{
var container = new Container();
Decoration.After = container;
return container;
return container.DebugPointer("Decoration After");
}
public void After(Action<IContainer> handler)
-1
View File
@@ -55,7 +55,6 @@ namespace QuestPDF.Fluent
public static class GridExtensions
{
[Obsolete("This element has been deprecated since version 2022.11. Please use the Table element, or the combination of the Row and Column elements.")]
public static void Grid(this IContainer element, Action<GridDescriptor> handler)
{
var descriptor = new GridDescriptor();
-1
View File
@@ -30,7 +30,6 @@ namespace QuestPDF.Fluent
public void BaselineMiddle() => Inlined.BaselineAlignment = VerticalAlignment.Middle;
public void BaselineBottom() => Inlined.BaselineAlignment = VerticalAlignment.Bottom;
internal void Alignment(InlinedAlignment? alignment) => Inlined.ElementsAlignment = alignment;
public void AlignLeft() => Inlined.ElementsAlignment = InlinedAlignment.Left;
public void AlignCenter() => Inlined.ElementsAlignment = InlinedAlignment.Center;
public void AlignRight() => Inlined.ElementsAlignment = InlinedAlignment.Right;
+1 -27
View File
@@ -10,9 +10,7 @@ namespace QuestPDF.Fluent
{
internal Page Page { get; } = new Page();
#region Size
public void Size(float width, float height, Unit unit = Unit.Point)
public void Size(float width, float height, Unit unit = Unit.Inch)
{
var pageSize = new PageSize(width, height, unit);
@@ -41,10 +39,6 @@ namespace QuestPDF.Fluent
{
Page.MaxSize = pageSize;
}
#endregion
#region Margin
public void MarginLeft(float value, Unit unit = Unit.Point)
{
@@ -84,10 +78,6 @@ namespace QuestPDF.Fluent
MarginHorizontal(value, unit);
}
#endregion
#region Properties
public void DefaultTextStyle(TextStyle textStyle)
{
Page.DefaultTextStyle = textStyle;
@@ -98,16 +88,6 @@ namespace QuestPDF.Fluent
DefaultTextStyle(handler(TextStyle.Default));
}
public void ContentFromLeftToRight()
{
Page.ContentDirection = ContentDirection.LeftToRight;
}
public void ContentFromRightToLeft()
{
Page.ContentDirection = ContentDirection.RightToLeft;
}
public void PageColor(string color)
{
Page.BackgroundColor = color;
@@ -119,10 +99,6 @@ namespace QuestPDF.Fluent
PageColor(color);
}
#endregion
#region Slots
public IContainer Background()
{
var container = new Container();
@@ -157,8 +133,6 @@ namespace QuestPDF.Fluent
Page.Footer = container;
return container;
}
#endregion
}
public static class PageExtensions
+1 -1
View File
@@ -22,7 +22,7 @@ namespace QuestPDF.Fluent
};
Row.Items.Add(element);
return element;
return element.DebugPointer("Row Item");
}
[Obsolete("This element has been renamed since version 2022.2. Please use the RelativeItem method.")]
+47 -48
View File
@@ -12,18 +12,11 @@ namespace QuestPDF.Fluent
{
public class TextSpanDescriptor
{
internal TextStyle TextStyle = TextStyle.Default;
internal Action<TextStyle> AssignTextStyle { get; }
internal TextStyle TextStyle { get; }
internal TextSpanDescriptor(Action<TextStyle> assignTextStyle)
internal TextSpanDescriptor(TextStyle textStyle)
{
AssignTextStyle = assignTextStyle;
}
internal void MutateTextStyle(Func<TextStyle, TextStyle> handler)
{
TextStyle = handler(TextStyle);
AssignTextStyle(TextStyle);
TextStyle = textStyle;
}
}
@@ -31,17 +24,16 @@ namespace QuestPDF.Fluent
public class TextPageNumberDescriptor : TextSpanDescriptor
{
internal Action<PageNumberFormatter> AssignFormatFunction { get; }
internal TextPageNumberDescriptor(Action<TextStyle> assignTextStyle, Action<PageNumberFormatter> assignFormatFunction) : base(assignTextStyle)
internal PageNumberFormatter FormatFunction { get; private set; } = x => x?.ToString() ?? string.Empty;
internal TextPageNumberDescriptor(TextStyle textStyle) : base(textStyle)
{
AssignFormatFunction = assignFormatFunction;
AssignFormatFunction(x => x?.ToString());
}
public TextPageNumberDescriptor Format(PageNumberFormatter formatter)
{
AssignFormatFunction(formatter);
FormatFunction = formatter ?? FormatFunction;
return this;
}
}
@@ -49,8 +41,8 @@ namespace QuestPDF.Fluent
public class TextDescriptor
{
private ICollection<TextBlock> TextBlocks { get; } = new List<TextBlock>();
private TextStyle? DefaultStyle { get; set; }
internal HorizontalAlignment? Alignment { get; set; }
private TextStyle DefaultStyle { get; set; } = TextStyle.Default;
internal HorizontalAlignment Alignment { get; set; } = HorizontalAlignment.Left;
private float Spacing { get; set; } = 0f;
public void DefaultTextStyle(TextStyle style)
@@ -62,7 +54,7 @@ namespace QuestPDF.Fluent
{
DefaultStyle = style(TextStyle.Default);
}
public void AlignLeft()
{
Alignment = HorizontalAlignment.Left;
@@ -99,15 +91,19 @@ namespace QuestPDF.Fluent
public TextSpanDescriptor Span(string? text)
{
var style = DefaultStyle.Clone();
var descriptor = new TextSpanDescriptor(style);
if (text == null)
return new TextSpanDescriptor(_ => { });
return descriptor;
var items = text
.Replace("\r", string.Empty)
.Split(new[] { '\n' }, StringSplitOptions.None)
.Select(x => new TextBlockSpan
{
Text = x
Text = x,
Style = style
})
.ToList();
@@ -122,7 +118,7 @@ namespace QuestPDF.Fluent
.ToList()
.ForEach(TextBlocks.Add);
return new TextSpanDescriptor(x => items.ForEach(y => y.Style = x));
return descriptor;
}
public TextSpanDescriptor Line(string? text)
@@ -138,10 +134,16 @@ namespace QuestPDF.Fluent
private TextPageNumberDescriptor PageNumber(Func<IPageContext, int?> pageNumber)
{
var textBlockItem = new TextBlockPageNumber();
AddItemToLastTextBlock(textBlockItem);
var style = DefaultStyle.Clone();
var descriptor = new TextPageNumberDescriptor(style);
return new TextPageNumberDescriptor(x => textBlockItem.Style = x, x => textBlockItem.Source = context => x(pageNumber(context)));
AddItemToLastTextBlock(new TextBlockPageNumber
{
Source = context => descriptor.FormatFunction(pageNumber(context)),
Style = style
});
return descriptor;
}
public TextPageNumberDescriptor CurrentPageNumber()
@@ -185,17 +187,20 @@ namespace QuestPDF.Fluent
if (IsNullOrEmpty(sectionName))
throw new ArgumentException("Section name cannot be null or empty", nameof(sectionName));
var style = DefaultStyle.Clone();
var descriptor = new TextSpanDescriptor(style);
if (IsNullOrEmpty(text))
return new TextSpanDescriptor(_ => { });
var textBlockItem = new TextBlockSectionLink
return descriptor;
AddItemToLastTextBlock(new TextBlockSectionLink
{
Style = style,
Text = text,
SectionName = sectionName
};
});
AddItemToLastTextBlock(textBlockItem);
return new TextSpanDescriptor(x => textBlockItem.Style = x);
return descriptor;
}
[Obsolete("This element has been renamed since version 2022.3. Please use the SectionLink method.")]
@@ -209,17 +214,20 @@ namespace QuestPDF.Fluent
if (IsNullOrEmpty(url))
throw new ArgumentException("Url cannot be null or empty", nameof(url));
var style = DefaultStyle.Clone();
var descriptor = new TextSpanDescriptor(style);
if (IsNullOrEmpty(text))
return new TextSpanDescriptor(_ => { });
return descriptor;
var textBlockItem = new TextBlockHyperlink
AddItemToLastTextBlock(new TextBlockHyperlink
{
Style = style,
Text = text,
Url = url
};
});
AddItemToLastTextBlock(textBlockItem);
return new TextSpanDescriptor(x => textBlockItem.Style = x);
return descriptor;
}
[Obsolete("This element has been renamed since version 2022.3. Please use the Hyperlink method.")]
@@ -242,24 +250,15 @@ namespace QuestPDF.Fluent
internal void Compose(IContainer container)
{
TextBlocks.ToList().ForEach(x => x.Alignment ??= Alignment);
if (DefaultStyle != null)
container = container.DefaultTextStyle(DefaultStyle);
TextBlocks.ToList().ForEach(x => x.Alignment = Alignment);
if (TextBlocks.Count == 1)
{
container.Element(TextBlocks.First());
return;
}
container.Column(column =>
container.DefaultTextStyle(DefaultStyle).Column(column =>
{
column.Spacing(Spacing);
foreach (var textBlock in TextBlocks)
column.Item().Element(textBlock);
});
});
}
}
+34 -69
View File
@@ -11,135 +11,120 @@ namespace QuestPDF.Fluent
if (style == null)
return descriptor;
descriptor.MutateTextStyle(x => x.OverrideStyle(style));
descriptor.TextStyle.OverrideStyle(style);
return descriptor;
}
public static T Fallback<T>(this T descriptor, TextStyle? value = null) where T : TextSpanDescriptor
{
descriptor.TextStyle.Fallback = value;
return descriptor;
}
public static T Fallback<T>(this T descriptor, Func<TextStyle, TextStyle> handler) where T : TextSpanDescriptor
{
return descriptor.Fallback(handler(TextStyle.Default));
}
public static T FontColor<T>(this T descriptor, string value) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.FontColor(value));
descriptor.TextStyle.Color = value;
return descriptor;
}
public static T BackgroundColor<T>(this T descriptor, string value) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.BackgroundColor(value));
descriptor.TextStyle.BackgroundColor = value;
return descriptor;
}
public static T FontFamily<T>(this T descriptor, string value) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.FontFamily(value));
descriptor.TextStyle.FontFamily = value;
return descriptor;
}
public static T FontSize<T>(this T descriptor, float value) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.FontSize(value));
descriptor.TextStyle.Size = value;
return descriptor;
}
public static T LineHeight<T>(this T descriptor, float value) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.LineHeight(value));
descriptor.TextStyle.LineHeight = value;
return descriptor;
}
public static T Italic<T>(this T descriptor, bool value = true) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Italic(value));
descriptor.TextStyle.IsItalic = value;
return descriptor;
}
public static T Strikethrough<T>(this T descriptor, bool value = true) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Strikethrough(value));
descriptor.TextStyle.HasStrikethrough = value;
return descriptor;
}
public static T Underline<T>(this T descriptor, bool value = true) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Underline(value));
descriptor.TextStyle.HasUnderline = value;
return descriptor;
}
public static T WrapAnywhere<T>(this T descriptor, bool value = true) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.WrapAnywhere(value));
descriptor.TextStyle.WrapAnywhere = value;
return descriptor;
}
#region Weight
public static T Weight<T>(this T descriptor, FontWeight weight) where T : TextSpanDescriptor
{
descriptor.TextStyle.FontWeight = weight;
return descriptor;
}
public static T Thin<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Thin());
return descriptor;
return descriptor.Weight(FontWeight.Thin);
}
public static T ExtraLight<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.ExtraLight());
return descriptor;
return descriptor.Weight(FontWeight.ExtraLight);
}
public static T Light<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Light());
return descriptor;
return descriptor.Weight(FontWeight.Light);
}
public static T NormalWeight<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.NormalWeight());
return descriptor;
return descriptor.Weight(FontWeight.Normal);
}
public static T Medium<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Medium());
return descriptor;
return descriptor.Weight(FontWeight.Medium);
}
public static T SemiBold<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.SemiBold());
return descriptor;
return descriptor.Weight(FontWeight.SemiBold);
}
public static T Bold<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Bold());
return descriptor;
return descriptor.Weight(FontWeight.Bold);
}
public static T ExtraBold<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.ExtraBold());
return descriptor;
return descriptor.Weight(FontWeight.ExtraBold);
}
public static T Black<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Black());
return descriptor;
return descriptor.Weight(FontWeight.Black);
}
public static T ExtraBlack<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.ExtraBlack());
return descriptor;
return descriptor.Weight(FontWeight.ExtraBlack);
}
#endregion
@@ -147,44 +132,24 @@ namespace QuestPDF.Fluent
#region Position
public static T NormalPosition<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.NormalPosition());
return descriptor;
return descriptor.Position(FontPosition.Normal);
}
public static T Subscript<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Subscript());
return descriptor;
return descriptor.Position(FontPosition.Subscript);
}
public static T Superscript<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.Superscript());
return descriptor;
}
#endregion
#region Direction
public static T DirectionAuto<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.DirectionAuto());
return descriptor;
}
public static T DirectionFromLeftToRight<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.DirectionFromLeftToRight());
return descriptor;
}
public static T DirectionFromRightToLeft<T>(this T descriptor) where T : TextSpanDescriptor
{
descriptor.MutateTextStyle(x => x.DirectionFromRightToLeft());
return descriptor;
return descriptor.Position(FontPosition.Superscript);
}
private static T Position<T>(this T descriptor, FontPosition fontPosition) where T : TextSpanDescriptor
{
descriptor.TextStyle.FontPosition = fontPosition;
return descriptor;
}
#endregion
}
}
+21 -50
View File
@@ -6,6 +6,14 @@ namespace QuestPDF.Fluent
{
public static class TextStyleExtensions
{
private static TextStyle Mutate(this TextStyle style, Action<TextStyle> handler)
{
style = style.Clone();
handler(style);
return style;
}
[Obsolete("This element has been renamed since version 2022.3. Please use the FontColor method.")]
public static TextStyle Color(this TextStyle style, string value)
{
@@ -14,12 +22,12 @@ namespace QuestPDF.Fluent
public static TextStyle FontColor(this TextStyle style, string value)
{
return style.Mutate(TextStyleProperty.Color, value);
return style.Mutate(x => x.Color = value);
}
public static TextStyle BackgroundColor(this TextStyle style, string value)
{
return style.Mutate(TextStyleProperty.BackgroundColor, value);
return style.Mutate(x => x.BackgroundColor = value);
}
[Obsolete("This element has been renamed since version 2022.3. Please use the FontFamily method.")]
@@ -30,7 +38,7 @@ namespace QuestPDF.Fluent
public static TextStyle FontFamily(this TextStyle style, string value)
{
return style.Mutate(TextStyleProperty.FontFamily, value);
return style.Mutate(x => x.FontFamily = value);
}
[Obsolete("This element has been renamed since version 2022.3. Please use the FontSize method.")]
@@ -41,39 +49,39 @@ namespace QuestPDF.Fluent
public static TextStyle FontSize(this TextStyle style, float value)
{
return style.Mutate(TextStyleProperty.Size, value);
return style.Mutate(x => x.Size = value);
}
public static TextStyle LineHeight(this TextStyle style, float value)
{
return style.Mutate(TextStyleProperty.LineHeight, value);
return style.Mutate(x => x.LineHeight = value);
}
public static TextStyle Italic(this TextStyle style, bool value = true)
{
return style.Mutate(TextStyleProperty.IsItalic, value);
return style.Mutate(x => x.IsItalic = value);
}
public static TextStyle Strikethrough(this TextStyle style, bool value = true)
{
return style.Mutate(TextStyleProperty.HasStrikethrough, value);
return style.Mutate(x => x.HasStrikethrough = value);
}
public static TextStyle Underline(this TextStyle style, bool value = true)
{
return style.Mutate(TextStyleProperty.HasUnderline, value);
return style.Mutate(x => x.HasUnderline = value);
}
public static TextStyle WrapAnywhere(this TextStyle style, bool value = true)
{
return style.Mutate(TextStyleProperty.WrapAnywhere, value);
return style.Mutate(x => x.WrapAnywhere = value);
}
#region Weight
public static TextStyle Weight(this TextStyle style, FontWeight weight)
{
return style.Mutate(TextStyleProperty.FontWeight, weight);
return style.Mutate(x => x.FontWeight = weight);
}
public static TextStyle Thin(this TextStyle style)
@@ -129,7 +137,6 @@ namespace QuestPDF.Fluent
#endregion
#region Position
public static TextStyle NormalPosition(this TextStyle style)
{
return style.Position(FontPosition.Normal);
@@ -147,47 +154,11 @@ namespace QuestPDF.Fluent
private static TextStyle Position(this TextStyle style, FontPosition fontPosition)
{
return style.Mutate(TextStyleProperty.FontPosition, fontPosition);
}
#endregion
if (style.FontPosition == fontPosition)
return style;
#region Fallback
public static TextStyle Fallback(this TextStyle style, TextStyle? value = null)
{
return style.Mutate(TextStyleProperty.Fallback, value);
return style.Mutate(t => t.FontPosition = fontPosition);
}
public static TextStyle Fallback(this TextStyle style, Func<TextStyle, TextStyle> handler)
{
return style.Fallback(handler(TextStyle.Default));
}
#endregion
#region Direction
private static TextStyle TextDirection(this TextStyle style, TextDirection textDirection)
{
return style.Mutate(TextStyleProperty.Direction, textDirection);
}
public static TextStyle DirectionAuto(this TextStyle style)
{
return style.TextDirection(Infrastructure.TextDirection.Auto);
}
public static TextStyle DirectionFromLeftToRight(this TextStyle style)
{
return style.TextDirection(Infrastructure.TextDirection.LeftToRight);
}
public static TextStyle DirectionFromRightToLeft(this TextStyle style)
{
return style.TextDirection(Infrastructure.TextDirection.RightToLeft);
}
#endregion
}
}
-1
View File
@@ -13,7 +13,6 @@
public const string CourierNew = "Courier New";
public const string Georgia = "Georgia";
public const string Impact = "Impact";
public const string Lato = "Lato";
public const string LucidaConsole = "Lucida Console";
public const string SegoeSD = "Segoe SD";
public const string SegoeUI = "Segoe UI";
+3 -12
View File
@@ -4,7 +4,6 @@ using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using QuestPDF.Drawing;
using QuestPDF.Infrastructure;
namespace QuestPDF.Helpers
@@ -42,23 +41,15 @@ namespace QuestPDF.Helpers
internal static string PrettifyName(this string text)
{
return Regex.Replace(text, @"([a-z])([A-Z])", "$1 $2", RegexOptions.Compiled);
return Regex.Replace(text, @"([a-z])([A-Z])", "$1 $2");
}
internal static void VisitChildren(this Element? element, Action<Element?> handler)
{
if (element == null)
return;
foreach (var child in element.GetChildren())
foreach (var child in element.GetChildren().Where(x => x != null))
VisitChildren(child, handler);
handler(element);
}
internal static bool IsNegative(this Size size)
{
return size.Width < 0f || size.Height < 0f;
}
}
}
@@ -1,8 +0,0 @@
namespace QuestPDF.Infrastructure
{
internal enum ContentDirection
{
LeftToRight,
RightToLeft
}
}
+6
View File
@@ -15,6 +15,12 @@ namespace QuestPDF.Infrastructure
yield break;
}
internal virtual void Initialize(IPageContext pageContext, ICanvas canvas)
{
PageContext = pageContext;
Canvas = canvas;
}
internal virtual void CreateProxy(Func<Element?, Element?> create)
{
@@ -1,7 +0,0 @@
namespace QuestPDF.Infrastructure
{
internal interface IContentDirectionAware
{
public ContentDirection ContentDirection { get; set; }
}
}
-9
View File
@@ -1,9 +0,0 @@
namespace QuestPDF.Infrastructure
{
internal enum TextDirection
{
Auto,
LeftToRight,
RightToLeft
}
}
+59 -10
View File
@@ -3,8 +3,10 @@ using QuestPDF.Helpers;
namespace QuestPDF.Infrastructure
{
public record TextStyle
public class TextStyle
{
internal bool HasGlobalStyleApplied { get; private set; }
internal string? Color { get; set; }
internal string? BackgroundColor { get; set; }
internal string? FontFamily { get; set; }
@@ -16,15 +18,15 @@ namespace QuestPDF.Infrastructure
internal bool? HasStrikethrough { get; set; }
internal bool? HasUnderline { get; set; }
internal bool? WrapAnywhere { get; set; }
internal TextDirection? Direction { get; set; }
internal TextStyle? Fallback { get; set; }
internal static TextStyle LibraryDefault { get; } = new()
internal object PaintKey { get; private set; }
internal object FontMetricsKey { get; private set; }
internal static TextStyle LibraryDefault => new TextStyle
{
Color = Colors.Black,
BackgroundColor = Colors.Transparent,
FontFamily = Fonts.Lato,
FontFamily = Fonts.Calibri,
Size = 12,
LineHeight = 1.2f,
FontWeight = Infrastructure.FontWeight.Normal,
@@ -32,11 +34,58 @@ namespace QuestPDF.Infrastructure
IsItalic = false,
HasStrikethrough = false,
HasUnderline = false,
WrapAnywhere = false,
Direction = TextDirection.Auto,
Fallback = null
WrapAnywhere = false
};
public static TextStyle Default { get; } = new();
public static TextStyle Default => new TextStyle();
internal void ApplyGlobalStyle(TextStyle globalStyle)
{
if (HasGlobalStyleApplied)
return;
HasGlobalStyleApplied = true;
ApplyParentStyle(globalStyle);
PaintKey ??= (FontFamily, Size, FontWeight, FontPosition, IsItalic, Color);
FontMetricsKey ??= (FontFamily, Size, FontWeight, IsItalic);
}
internal void ApplyParentStyle(TextStyle parentStyle)
{
Color ??= parentStyle.Color;
BackgroundColor ??= parentStyle.BackgroundColor;
FontFamily ??= parentStyle.FontFamily;
Size ??= parentStyle.Size;
LineHeight ??= parentStyle.LineHeight;
FontWeight ??= parentStyle.FontWeight;
FontPosition ??= parentStyle.FontPosition;
IsItalic ??= parentStyle.IsItalic;
HasStrikethrough ??= parentStyle.HasStrikethrough;
HasUnderline ??= parentStyle.HasUnderline;
WrapAnywhere ??= parentStyle.WrapAnywhere;
}
internal void OverrideStyle(TextStyle parentStyle)
{
Color = parentStyle.Color ?? Color;
BackgroundColor = parentStyle.BackgroundColor ?? BackgroundColor;
FontFamily = parentStyle.FontFamily ?? FontFamily;
Size = parentStyle.Size ?? Size;
LineHeight = parentStyle.LineHeight ?? LineHeight;
FontWeight = parentStyle.FontWeight ?? FontWeight;
FontPosition = parentStyle.FontPosition ?? FontPosition;
IsItalic = parentStyle.IsItalic ?? IsItalic;
HasStrikethrough = parentStyle.HasStrikethrough ?? HasStrikethrough;
HasUnderline = parentStyle.HasUnderline ?? HasUnderline;
WrapAnywhere = parentStyle.WrapAnywhere ?? WrapAnywhere;
}
internal TextStyle Clone()
{
var clone = (TextStyle)MemberwiseClone();
clone.HasGlobalStyleApplied = false;
return clone;
}
}
}
-263
View File
@@ -1,263 +0,0 @@
using System;
using System.Collections.Concurrent;
using QuestPDF.Fluent;
namespace QuestPDF.Infrastructure
{
internal enum TextStyleProperty
{
Color,
BackgroundColor,
FontFamily,
Size,
LineHeight,
FontWeight,
FontPosition,
IsItalic,
HasStrikethrough,
HasUnderline,
WrapAnywhere,
Fallback,
Direction
}
internal static class TextStyleManager
{
private static readonly ConcurrentDictionary<(TextStyle origin, TextStyleProperty property, object value), TextStyle> TextStyleMutateCache = new();
private static readonly ConcurrentDictionary<(TextStyle origin, TextStyle parent), TextStyle> TextStyleApplyGlobalCache = new();
private static readonly ConcurrentDictionary<(TextStyle origin, TextStyle parent), TextStyle> TextStyleOverrideCache = new();
public static TextStyle Mutate(this TextStyle origin, TextStyleProperty property, object value)
{
var cacheKey = (origin, property, value);
return TextStyleMutateCache.GetOrAdd(cacheKey, x => MutateStyle(x.origin, x.property, x.value));
}
private static TextStyle MutateStyle(TextStyle origin, TextStyleProperty property, object? value, bool overrideValue = true)
{
if (overrideValue && value == null)
return origin;
if (property == TextStyleProperty.Color)
{
if (!overrideValue && origin.Color != null)
return origin;
var castedValue = (string?)value;
if (origin.Color == castedValue)
return origin;
return origin with { Color = castedValue };
}
if (property == TextStyleProperty.BackgroundColor)
{
if (!overrideValue && origin.BackgroundColor != null)
return origin;
var castedValue = (string?)value;
if (origin.BackgroundColor == castedValue)
return origin;
return origin with { BackgroundColor = castedValue };
}
if (property == TextStyleProperty.FontFamily)
{
if (!overrideValue && origin.FontFamily != null)
return origin;
var castedValue = (string?)value;
if (origin.FontFamily == castedValue)
return origin;
return origin with { FontFamily = castedValue };
}
if (property == TextStyleProperty.Size)
{
if (!overrideValue && origin.Size != null)
return origin;
var castedValue = (float?)value;
if (origin.Size == castedValue)
return origin;
return origin with { Size = castedValue };
}
if (property == TextStyleProperty.LineHeight)
{
if (!overrideValue && origin.LineHeight != null)
return origin;
var castedValue = (float?)value;
if (origin.LineHeight == castedValue)
return origin;
return origin with { LineHeight = castedValue };
}
if (property == TextStyleProperty.FontWeight)
{
if (!overrideValue && origin.FontWeight != null)
return origin;
var castedValue = (FontWeight?)value;
if (origin.FontWeight == castedValue)
return origin;
return origin with { FontWeight = castedValue };
}
if (property == TextStyleProperty.FontPosition)
{
if (!overrideValue && origin.FontPosition != null)
return origin;
var castedValue = (FontPosition?)value;
if (origin.FontPosition == castedValue)
return origin;
return origin with { FontPosition = castedValue };
}
if (property == TextStyleProperty.IsItalic)
{
if (!overrideValue && origin.IsItalic != null)
return origin;
var castedValue = (bool?)value;
if (origin.IsItalic == castedValue)
return origin;
return origin with { IsItalic = castedValue };
}
if (property == TextStyleProperty.HasStrikethrough)
{
if (!overrideValue && origin.HasStrikethrough != null)
return origin;
var castedValue = (bool?)value;
if (origin.HasStrikethrough == castedValue)
return origin;
return origin with { HasStrikethrough = castedValue };
}
if (property == TextStyleProperty.HasUnderline)
{
if (!overrideValue && origin.HasUnderline != null)
return origin;
var castedValue = (bool?)value;
if (origin.HasUnderline == castedValue)
return origin;
return origin with { HasUnderline = castedValue };
}
if (property == TextStyleProperty.WrapAnywhere)
{
if (!overrideValue && origin.WrapAnywhere != null)
return origin;
var castedValue = (bool?)value;
if (origin.WrapAnywhere == castedValue)
return origin;
return origin with { WrapAnywhere = castedValue };
}
if (property == TextStyleProperty.Fallback)
{
if (!overrideValue && origin.Fallback != null)
return origin;
var castedValue = (TextStyle?)value;
if (origin.Fallback == castedValue)
return origin;
return origin with { Fallback = castedValue };
}
if (property == TextStyleProperty.Direction)
{
if (!overrideValue && origin.Direction != null)
return origin;
var castedValue = (TextDirection?)value;
if (origin.Direction == castedValue)
return origin;
return origin with { Direction = castedValue };
}
throw new ArgumentOutOfRangeException(nameof(property), property, "Expected to mutate the TextStyle object. Provided property type is not supported.");
}
internal static TextStyle ApplyGlobalStyle(this TextStyle style, TextStyle parent)
{
var cacheKey = (style, parent);
return TextStyleApplyGlobalCache.GetOrAdd(cacheKey, key => ApplyStyle(key.origin, key.parent, overrideStyle: false).ApplyFontFallback());
}
private static TextStyle ApplyFontFallback(this TextStyle style)
{
var targetFallbackStyle = style
?.Fallback
?.ApplyStyle(style, overrideStyle: false, applyFallback: false)
?.ApplyFontFallback();
return MutateStyle(style, TextStyleProperty.Fallback, targetFallbackStyle);
}
internal static TextStyle OverrideStyle(this TextStyle style, TextStyle parent)
{
var cacheKey = (style, parent);
return TextStyleOverrideCache.GetOrAdd(cacheKey, key =>
{
var result = ApplyStyle(key.origin, key.parent);
return MutateStyle(result, TextStyleProperty.Fallback, key.parent.Fallback);
});
}
private static TextStyle ApplyStyle(this TextStyle style, TextStyle parent, bool overrideStyle = true, bool applyFallback = true)
{
var result = style;
result = MutateStyle(result, TextStyleProperty.Color, parent.Color, overrideStyle);
result = MutateStyle(result, TextStyleProperty.BackgroundColor, parent.BackgroundColor, overrideStyle);
result = MutateStyle(result, TextStyleProperty.FontFamily, parent.FontFamily, overrideStyle);
result = MutateStyle(result, TextStyleProperty.Size, parent.Size, overrideStyle);
result = MutateStyle(result, TextStyleProperty.LineHeight, parent.LineHeight, overrideStyle);
result = MutateStyle(result, TextStyleProperty.FontWeight, parent.FontWeight, overrideStyle);
result = MutateStyle(result, TextStyleProperty.FontPosition, parent.FontPosition, overrideStyle);
result = MutateStyle(result, TextStyleProperty.IsItalic, parent.IsItalic, overrideStyle);
result = MutateStyle(result, TextStyleProperty.HasStrikethrough, parent.HasStrikethrough, overrideStyle);
result = MutateStyle(result, TextStyleProperty.HasUnderline, parent.HasUnderline, overrideStyle);
result = MutateStyle(result, TextStyleProperty.WrapAnywhere, parent.WrapAnywhere, overrideStyle);
result = MutateStyle(result, TextStyleProperty.Direction, parent.Direction, overrideStyle);
if (applyFallback)
result = MutateStyle(result, TextStyleProperty.Fallback, parent.Fallback, overrideStyle);
return result;
}
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ namespace QuestPDF.Previewer
public event Action? OnPreviewerStopped;
private const int RequiredPreviewerVersionMajor = 2022;
private const int RequiredPreviewerVersionMinor = 11;
private const int RequiredPreviewerVersionMinor = 6;
public PreviewerService(int port)
{
+2 -22
View File
@@ -3,7 +3,7 @@
<Authors>MarcinZiabek</Authors>
<Company>CodeFlint</Company>
<PackageId>QuestPDF</PackageId>
<Version>2022.11.0-alpha1</Version>
<Version>2022.6.2</Version>
<PackageDescription>QuestPDF is an open-source, modern and battle-tested library that can help you with generating PDF documents by offering friendly, discoverable and predictable C# fluent API.</PackageDescription>
<PackageReleaseNotes>$([System.IO.File]::ReadAllText("$(MSBuildProjectDirectory)/Resources/ReleaseNotes.txt"))</PackageReleaseNotes>
<LangVersion>9</LangVersion>
@@ -17,7 +17,7 @@
<PackageTags>pdf report file export generate generation tool create creation render portable document format quest html library converter open source free standard core</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Nullable>enable</Nullable>
<TargetFrameworks>net462;netstandard2.0;netcoreapp2.0;netcoreapp3.0;net6.0</TargetFrameworks>
<TargetFramework>net6.0</TargetFramework>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
@@ -44,25 +44,5 @@
<Visible>false</Visible>
<PackagePath>\</PackagePath>
</None>
<None Remove="Resources\DefaultFont\Lato-Black.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Black.ttf" />
<None Remove="Resources\DefaultFont\Lato-BlackItalic.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-BlackItalic.ttf" />
<None Remove="Resources\DefaultFont\Lato-Bold.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Bold.ttf" />
<None Remove="Resources\DefaultFont\Lato-BoldItalic.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-BoldItalic.ttf" />
<None Remove="Resources\DefaultFont\Lato-Italic.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Italic.ttf" />
<None Remove="Resources\DefaultFont\Lato-Light.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Light.ttf" />
<None Remove="Resources\DefaultFont\Lato-LightItalic.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-LightItalic.ttf" />
<None Remove="Resources\DefaultFont\Lato-Regular.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Regular.ttf" />
<None Remove="Resources\DefaultFont\Lato-Thin.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-Thin.ttf" />
<None Remove="Resources\DefaultFont\Lato-ThinItalic.ttf" />
<EmbeddedResource Include="Resources\DefaultFont\Lato-ThinItalic.ttf" />
</ItemGroup>
</Project>
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-93
View File
@@ -1,93 +0,0 @@
Copyright (c) 2010-2014 by tyPoland Lukasz Dziedzic (team@latofonts.com) with Reserved Font Name "Lato"
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+1 -1
View File
@@ -21,7 +21,7 @@ Install-Package QuestPDF
dotnet add package QuestPDF
// Package reference in .csproj file
<PackageReference Include="QuestPDF" Version="2022.11.0" />
<PackageReference Include="QuestPDF" Version="2022.3.0" />
```
## Documentation
Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 14 KiB

-78
View File
@@ -1,78 +0,0 @@
[![Dotnet](https://img.shields.io/badge/platform-.NET-blue)](https://www.nuget.org/packages/QuestPDF/)
[![GitHub Repo stars](https://img.shields.io/github/stars/QuestPDF/QuestPDF)](https://github.com/QuestPDF/QuestPDF/stargazers)
[![Nuget version](https://img.shields.io/nuget/v/QuestPdf)](https://www.nuget.org/packages/QuestPDF/)
[![Nuget download](https://img.shields.io/nuget/dt/QuestPDF)](https://www.nuget.org/packages/QuestPDF/)
[![License](https://img.shields.io/github/license/QuestPDF/QuestPDF)](https://github.com/QuestPDF/QuestPDF/blob/main/LICENSE)
[![Sponsor project](https://img.shields.io/badge/sponsor-project-red)](https://github.com/sponsors/QuestPDF)
QuestPDF is an open-source .NET library for PDF documents generation.
It offers a layout engine designed with a full paging support in mind. The document consists of many simple elements (e.g. border, background, image, text, padding, table, grid etc.) that are composed together to create more complex structures. This way, as a developer, you can understand the behavior of every element and use them with full confidence. Additionally, the document and all its elements support paging functionality. For example, an element can be moved to the next page (if there is not enough space) or even be split between pages like table's rows.
## Documentation
[![Getting started tutorial]( https://img.shields.io/badge/%F0%9F%9A%80%20read-getting%20started-blue)](https://www.questpdf.com/getting-started.html)
A short and easy to follow tutorial showing how to design an invoice document under 200 lines of code.
[![API reference](https://img.shields.io/badge/%F0%9F%93%96%20read-API%20reference-blue)](https://www.questpdf.com/api-reference/index.html)
A detailed description of behavior of all available components and how to use them with C# Fluent API.
[![Patterns and Practices](https://img.shields.io/badge/%F0%9F%94%8D%20read-patterns%20and%20practices-blue)](https://www.questpdf.com/design-patterns.html)
Everything that may help you designing great reports and create reusable code that is easy to maintain.
## Simplicity is the key
How easy it is to start and prototype with QuestPDF? Really easy thanks to its minimal API! Please analyse the code below:
```#
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
// code in your main method
Document.Create(container =>
{
container.Page(page =>
{
page.Size(PageSizes.A4);
page.Margin(2, Unit.Centimetre);
page.Background(Colors.White);
page.DefaultTextStyle(x => x.FontSize(20));
page.Header()
.Text("Hello PDF!")
.SemiBold().FontSize(36).FontColor(Colors.Blue.Medium);
page.Content()
.PaddingVertical(1, Unit.Centimetre)
.Column(x =>
{
x.Spacing(20);
x.Item().Text(Placeholders.LoremIpsum());
x.Item().Image(Placeholders.Image(200, 100));
});
page.Footer()
.AlignCenter()
.Text(x =>
{
x.Span("Page ");
x.CurrentPageNumber();
});
});
})
.GeneratePdf("hello.pdf");
```
And compare it to the produced PDF file:
![invoice](https://raw.githubusercontent.com/QuestPDF/QuestPDF-Documentation/main/docs/public/minimal-example-shadow.png)
## Are you ready for more?
The Fluent API of QuestPDF scales really well. It is easy to create and maintain even most complex documents. Read [the Getting started tutorial](https://www.questpdf.com/documentation/getting-started.html) to learn QuestPDF basics and implement an invoice under 200 lines of code. You can also investigate and play with the code from [the example repository](https://github.com/QuestPDF/example-invoice).
![invoice](https://raw.githubusercontent.com/QuestPDF/QuestPDF-Documentation/main/docs/public/invoice-small.png)
+9 -3
View File
@@ -1,3 +1,9 @@
Added support for the right-to-left content direction.
Fixed: word-wrapping algorithm does not work correctly with right-to-left languages.
Fixed: Page.Size() API incorrectly uses Unit.Inch as default unit. Replaced with Unit.Point for consistency.
Integrated the text-shaping algorithm. This change significantly improves the Unicode compatibility. Also, it extends support for more advanced languages (e.g. Arabic) that:
1) Combine multiple text characters and display them as a single visual glyph.
2) Are displayed in the right-to-left order.
Improved the exception message when SkiaSharp throws the TypeInitializationException. On some operating systems, SkiaSharp requires additional dependencies installed as nuget packages. This change should help developers determine how to choose and install them correctly.
Fixed: a rare case when the Row.AutoItem() does not correctly calculate the width of its content.
Fixed: the QuestPDF Previewer does not work with content-rich documents.
-40
View File
@@ -1,40 +0,0 @@
namespace QuestPDF
{
public static class Settings
{
/// <summary>
/// This value represents the maximum length of the document that the library produces.
/// This is useful when layout constraints are too strong, e.g. one element does not fit in another.
/// In such cases, the library would produce document of infinite length, consuming all available resources.
/// To break the algorithm and save the environment, the library breaks the rendering process after reaching specified length of document.
/// If your content requires generating longer documents, please assign the most reasonable value.
/// </summary>
public static int DocumentLayoutExceptionThreshold { get; set; } = 250;
/// <summary>
/// This flag generates additional document elements to cache layout calculation results.
/// In the vast majority of cases, this significantly improves performance, while slightly increasing memory consumption.
/// </summary>
/// <remarks>By default, this flag is enabled only when the debugger is NOT attached.</remarks>
public static bool EnableCaching { get; set; } = !System.Diagnostics.Debugger.IsAttached;
/// <summary>
/// This flag generates additional document elements to improve layout debugging experience.
/// When the DocumentLayoutException is thrown, the library is able to provide additional execution context.
/// It includes layout calculation results and path to the problematic area.
/// </summary>
/// <remarks>By default, this flag is enabled only when the debugger IS attached.</remarks>
public static bool EnableDebugging { get; set; } = System.Diagnostics.Debugger.IsAttached;
/// <summary>
/// This flag enables checking the font glyph availability.
/// If your text contains glyphs that are not present in the specified font,
/// 1) when this flag is enabled: the DocumentDrawingException is thrown. OR
/// 2) when this flag is disabled: placeholder characters are visible in the produced PDF file.
/// Enabling this flag may slightly decrease document generation performance.
/// However, it provides hints that used fonts are not sufficient to produce correct results.
/// </summary>
/// <remarks>By default, this flag is enabled only when the debugger IS attached.</remarks>
public static bool CheckIfAllTextGlyphsAreAvailable { get; set; } = System.Diagnostics.Debugger.IsAttached;
}
}
+15 -16
View File
@@ -1,5 +1,5 @@
<a href="https://www.questpdf.com/" target="_blank">
<img src="https://github.com/QuestPDF/example-invoice/raw/main/images/logo.svg" width="400">
<img src="https://github.com/QuestPDF/example-invoice/raw/main/images/logo.svg" width="300">
</a>
---
@@ -17,15 +17,12 @@ It offers a layouting engine designed with a full paging support in mind. The do
Unlike other libraries, it does not rely on the HTML-to-PDF conversion which in many cases is not reliable. Instead, it implements its own layouting engine that is optimized to cover all paging-related requirements.
## Please help by giving a star
## Please show the value
Choosing a project dependency could be difficult. We need to ensure stability and maintainability of our projects. Surveys show that GitHub stars count play an important factor when assessing library quality.
⭐ Please give this repository a star. It takes seconds and help thousands of developers! ⭐
<img src="https://user-images.githubusercontent.com/9263853/190931857-8ca52ec8-cc7d-4d12-9467-4442b3342fa1.png" width="700" />
## Please share with the community
As an open-source project without funding, I cannot afford advertising QuestPDF in a typical way. Instead, the library relies on community interactions. Please consider sharing a post about QuestPDF and the value it provides. It really does help!
@@ -47,7 +44,6 @@ Special thanks to all companies that decided to sponsor QuestPDF development. Th
| Company | Description |
|--------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------|
| <img src="Resources/jetbrains-logo.svg" width="100px"> | [JetBrains](https://www.jetbrains.com/) supports this project as part of the OSS Power-Ups program. Thank you!<br/>100$ / month |
| <img src="https://avatars.githubusercontent.com/u/2712328?v=4" width="100px"> | [Mark Gould](https://github.com/markgould) supports this project. Thank you!<br/>100$ / month |
[![Sponsor project](https://img.shields.io/badge/%E2%9D%A4%EF%B8%8F%20sponsor-QuestPDF-red)](https://github.com/sponsors/QuestPDF)
@@ -63,32 +59,35 @@ Install-Package QuestPDF
dotnet add package QuestPDF
// Package reference in .csproj file
<PackageReference Include="QuestPDF" Version="2022.9.0" />
<PackageReference Include="QuestPDF" Version="2022.6.0" />
```
[![Nuget version](https://img.shields.io/badge/package%20details-QuestPDF-blue?logo=nuget)](https://www.nuget.org/packages/QuestPDF/)
## Documentation
[![Getting started tutorial]( https://img.shields.io/badge/%F0%9F%9A%80%20read-getting%20started-blue)](https://www.questpdf.com/getting-started)
[![Getting started tutorial]( https://img.shields.io/badge/%F0%9F%9A%80%20read-getting%20started-blue)](https://www.questpdf.com/documentation/getting-started.html)
A short and easy to follow tutorial showing how to design an invoice document under 200 lines of code.
[![API reference](https://img.shields.io/badge/%F0%9F%93%96%20read-API%20reference-blue)](https://www.questpdf.com/api-reference/index.html)
[![API reference](https://img.shields.io/badge/%F0%9F%93%96%20read-API%20reference-blue)](https://www.questpdf.com/documentation/api-reference.html)
A detailed description of behavior of all available components and how to use them with C# Fluent API.
[![Patterns and Practices](https://img.shields.io/badge/%E2%9C%A8%20read-patterns%20and%20practices-blue)](https://www.questpdf.com/design-patterns)
[![Patterns and Practices](https://img.shields.io/badge/%E2%9C%A8%20read-patterns%20and%20practices-blue)](https://www.questpdf.com/documentation/patterns-and-practices.html#document-metadata)
Everything that may help you designing great reports and create reusable code that is easy to maintain.
## QuestPDF Previewer
The QuestPDF Previewer is a tool designed to simplify and speed up your development lifecycle. First, it shows a preview of your document. But the real magic starts with the hot-reload capability! It observes your code and updates the preview every time you change the implementation. Get real-time results without the need of code recompilation. Save time and enjoy the task!
[![Learn more](https://img.shields.io/badge/%F0%9F%93%96%20Previewer-learn%20more-blue)](https://www.questpdf.com/document-previewer)
[![Learn more](https://img.shields.io/badge/%F0%9F%93%96%20Previewer-learn%20more-blue)](https://www.questpdf.com/documentation/document-previewer.html)
<video src="https://github.com/QuestPDF/QuestPDF-Documentation/blob/a6f54912ee761af14dfbe1f96aa70d7fcf7ff94f/images/previewer/video.mp4?raw=true"></video>
<img src="https://github.com/QuestPDF/QuestPDF-Documentation/blob/main/docs/public/previewer/animation.gif?raw=true" width="100%">
<img src="https://raw.githubusercontent.com/QuestPDF/QuestPDF-Documentation/main/images/previewer/animation.gif" width="100%">
## Simplicity is the key
@@ -137,13 +136,13 @@ Document.Create(container =>
And compare it to the produced PDF file:
<img src="https://github.com/QuestPDF/QuestPDF-Documentation/blob/main/docs/public/minimal-example-shadow.png?raw=true" width="250px">
<img src="https://raw.githubusercontent.com/QuestPDF/QuestPDF-Documentation/main/images/minimal-api.png" width="250px">
## Are you ready for more?
The Fluent API of QuestPDF scales really well. It is easy to create and maintain even most complex documents. Read [the Getting started tutorial](https://www.questpdf.com/getting-started.html) to learn QuestPDF basics and implement an invoice under 200 lines of code. You can also investigate and play with the code from [the example repository](https://github.com/QuestPDF/example-invoice).
The Fluent API of QuestPDF scales really well. It is easy to create and maintain even most complex documents. Read [the Getting started tutorial](https://www.questpdf.com/documentation/getting-started.html) to learn QuestPDF basics and implement an invoice under 200 lines of code. You can also investigate and play with the code from [the example repository](https://github.com/QuestPDF/example-invoice).
<img src="https://github.com/QuestPDF/QuestPDF-Documentation/blob/main/docs/public/invoice-small.png?raw=true" width="400px">
<img src="https://github.com/QuestPDF/example-invoice/raw/main/images/invoice.png" width="400px">
## QuestPDF on JetBrains OSS Power-Ups
@@ -151,7 +150,7 @@ The Fluent API of QuestPDF scales really well. It is easy to create and maintain
QuestPDF was presented on one of the episodes of OSS Power-Ups hosted by JetBrains. Huge thanks for Matthias Koch and entire JetBrains team for giving me a chance to show QuestPDF. You are the best!
<a href="https://www.youtube.com/watch?v=-iYvZvpLX0g">
<img src="https://github.com/QuestPDF/QuestPDF-Documentation/blob/main/docs/public/jetbrains-oss-powerups-youtube.png?raw=true" width="600px">
<img src="https://raw.githubusercontent.com/QuestPDF/QuestPDF-Documentation/main/images/jetbrains-oss-powerups-youtube.png" width="600px">
</a>