-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathSvgTextExporter.cs
266 lines (228 loc) · 8.96 KB
/
SvgTextExporter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
namespace UglyToad.PdfPig.DocumentLayoutAnalysis.Export
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Xml;
using Content;
using Graphics;
using Graphics.Colors;
using Graphics.Core;
/// <summary>
/// Exports a page as an SVG.
/// </summary>
public sealed class SvgTextExporter : ITextExporter
{
private readonly Func<string, string> invalidCharacterHandler;
private static readonly Dictionary<string, string> Fonts = new Dictionary<string, string>()
{
{ "ArialMT", "Arial Rounded MT Bold" }
};
/// <summary>
/// Used to round numbers.
/// </summary>
public int Rounding { get; } = 4;
/// <summary>
/// <inheritdoc/>
/// Not in use.
/// </summary>
public InvalidCharStrategy InvalidCharStrategy { get; }
/// <summary>
/// Svg text exporter.
/// </summary>
/// <param name="invalidCharacterHandler">How to handle invalid characters.</param>
public SvgTextExporter(Func<string, string> invalidCharacterHandler)
: this(InvalidCharStrategy.Custom, invalidCharacterHandler)
{ }
/// <summary>
/// Svg text exporter.
/// </summary>
/// <param name="invalidCharacterStrategy">How to handle invalid characters.</param>
public SvgTextExporter(InvalidCharStrategy invalidCharacterStrategy = InvalidCharStrategy.DoNotCheck)
: this(invalidCharacterStrategy, null)
{ }
private SvgTextExporter(InvalidCharStrategy invalidCharacterStrategy, Func<string, string> invalidCharacterHandler)
{
InvalidCharStrategy = invalidCharacterStrategy;
if (invalidCharacterHandler is null)
{
this.invalidCharacterHandler = TextExporterHelper.GetXmlInvalidCharHandler(InvalidCharStrategy);
}
else
{
this.invalidCharacterHandler = invalidCharacterHandler;
}
}
/// <summary>
/// Get the page contents as an SVG.
/// </summary>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("'RequiresUnreferencedCodeAttribute' annotations must match across all interface implementations or overrides.")]
#endif
public string Get(Page page)
{
var builder = new StringBuilder($"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width='{Math.Round(page.Width, Rounding)}' height='{Math.Round(page.Height, Rounding)}'>\n<g transform=\"scale(1, 1) translate(0, 0)\">\n");
foreach (var path in page.Paths)
{
if (!path.IsClipping)
{
builder.AppendLine(PathToSvg(path, page.Height));
}
}
var doc = new XmlDocument();
foreach (var letter in page.Letters)
{
builder.Append(LetterToSvg(letter, page.Height, doc));
}
builder.Append("</g></svg>");
return builder.ToString();
}
private string LetterToSvg(Letter l, double height, XmlDocument doc)
{
string fontFamily = GetFontFamily(l.FontName, out string style, out string weight);
string rotation = "";
if (l.GlyphRectangle.Rotation != 0)
{
rotation = $" transform='rotate({Math.Round(-l.GlyphRectangle.Rotation, Rounding)} {Math.Round(l.GlyphRectangle.BottomLeft.X, Rounding)},{Math.Round(height - l.GlyphRectangle.TopLeft.Y, Rounding)})'";
}
string fontSize = l.FontSize != 1 ? $"font-size='{l.FontSize:0}'" : $"style='font-size:{Math.Round(l.GlyphRectangle.Height, 2)}px'";
var safeValue = XmlEscape(l, doc);
var x = Math.Round(l.StartBaseLine.X, Rounding);
var y = Math.Round(height - l.StartBaseLine.Y, Rounding);
return $"<text x='{x}' y='{y}'{rotation} font-family='{fontFamily}' font-style='{style}' font-weight='{weight}' {fontSize} fill='{ColorToSvg(l.Color)}'>{safeValue}</text>"
+ Environment.NewLine;
}
private static string GetFontFamily(string fontName, out string style, out string weight)
{
style = "normal"; // normal | italic | oblique
weight = "normal"; // normal | bold | bolder | lighter
// remove subset prefix
if (fontName.Contains('+'))
{
if (fontName.Length > 7 && fontName[6] == '+')
{
var split = fontName.Split('+');
if (split[0].All(char.IsUpper))
{
fontName = split[1];
}
}
}
if (fontName.Contains('-'))
{
var infos = fontName.Split('-');
fontName = infos[0];
for (int i = 1; i < infos.Length; i++)
{
string infoLower = infos[i].ToLowerInvariant();
if (infoLower.Contains("light"))
{
weight = "lighter";
}
else if (infoLower.Contains("bolder"))
{
weight = "bolder";
}
else if (infoLower.Contains("bold"))
{
weight = "bold";
}
if (infoLower.Contains("italic"))
{
style = "italic";
}
else if (infoLower.Contains("oblique"))
{
style = "oblique";
}
}
}
if (Fonts.ContainsKey(fontName))
{
fontName = Fonts[fontName];
}
return fontName;
}
private string XmlEscape(Letter letter, XmlDocument doc)
{
XmlNode node = doc.CreateElement("root");
node.InnerText = invalidCharacterHandler(letter.Value);
return node.InnerXml;
}
private static string ColorToSvg(IColor color)
{
if (color == null)
{
return string.Empty;
}
var (r, g, b) = color.ToRGBValues();
return $"rgb({Convert.ToByte(r * 255)},{Convert.ToByte(g * 255)},{Convert.ToByte(b * 255)})";
}
private static string PathToSvg(PdfPath p, double height)
{
var builder = new StringBuilder();
foreach (var subpath in p)
{
foreach (var command in subpath.Commands)
{
command.WriteSvg(builder, height);
}
}
if (builder.Length == 0)
{
return string.Empty;
}
if (builder[builder.Length - 1] == ' ')
{
builder.Remove(builder.Length - 1, 1);
}
var glyph = builder.ToString();
string dashArray = "";
string capStyle = "";
string jointStyle = "";
string strokeColor = " stroke='none'";
string strokeWidth = "";
if (p.IsStroked)
{
strokeColor = $" stroke='{ColorToSvg(p.StrokeColor)}'";
strokeWidth = $" stroke-width='{p.LineWidth}'";
if (p.LineDashPattern.HasValue && p.LineDashPattern.Value.Array.Count > 0)
{
dashArray = $" stroke-dasharray='{string.Join(" ", p.LineDashPattern.Value.Array)}'";
}
if (p.LineCapStyle != LineCapStyle.Butt)
{
if (p.LineCapStyle == LineCapStyle.Round)
{
capStyle = " stroke-linecap='round'";
}
else
{
capStyle = " stroke-linecap='square'";
}
}
if (p.LineJoinStyle != LineJoinStyle.Miter)
{
if (p.LineJoinStyle == LineJoinStyle.Round)
{
jointStyle = " stroke-linejoin='round'";
}
else
{
jointStyle = " stroke-linejoin='bevel'";
}
}
}
string fillColor = " fill='none'";
const string fillRule = ""; // For further dev
if (p.IsFilled)
{
fillColor = $" fill='{ColorToSvg(p.FillColor)}'";
}
var path = $"<path d='{glyph}'{fillColor}{fillRule}{strokeColor}{strokeWidth}{dashArray}{capStyle}{jointStyle}></path>";
return path;
}
}
}