-
Notifications
You must be signed in to change notification settings - Fork 478
/
Copy pathSvgDocument.cs
772 lines (679 loc) · 30.2 KB
/
SvgDocument.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Text;
using System.Xml;
using System.Linq;
using Svg.ExCSS;
using Svg.Css;
using System.Threading;
using System.Globalization;
using Svg.Exceptions;
using System.Runtime.InteropServices;
namespace Svg
{
/// <summary>
/// The class used to create and load SVG documents.
/// </summary>
public class SvgDocument : SvgFragment, ITypeDescriptorContext
{
/// <summary>
/// Skip check whether the GDI+ can be loaded.
/// </summary>
/// <remarks>
/// Set to true on systems that do not support GDI+ like UWP.
/// </remarks>
public static bool SkipGdiPlusCapabilityCheck { get; set; }
public static readonly int PointsPerInch = GetSystemDpi();
private SvgElementIdManager _idManager;
private Dictionary<string, IEnumerable<SvgFontFace>> _fontDefns = null;
public override SvgOverflow Overflow
{
get { return GetAttribute("overflow", false, SvgOverflow.Visible); }
}
private static int GetSystemDpi()
{
bool isWindows;
#if NETCORE
isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#else
var platform = Environment.OSVersion.Platform;
isWindows = platform == PlatformID.Win32NT;
#endif
if (isWindows)
{
// NOTE: starting with Windows 8.1, the DPI is no longer system-wide but screen-specific
IntPtr hDC = GetDC(IntPtr.Zero);
const int LOGPIXELSY = 90;
int result = GetDeviceCaps(hDC, LOGPIXELSY);
ReleaseDC(IntPtr.Zero, hDC);
return result;
}
else
{
// hack for macOS and Linux
return 96;
}
}
[DllImport("gdi32.dll")]
private static extern int GetDeviceCaps(IntPtr hdc, int nIndex);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
internal Dictionary<string, IEnumerable<SvgFontFace>> FontDefns()
{
if (_fontDefns == null)
{
_fontDefns = (from f in Descendants().OfType<SvgFontFace>()
group f by f.FontFamily into family
select family).ToDictionary(f => f.Key, f => (IEnumerable<SvgFontFace>)f);
}
return _fontDefns;
}
/// <summary>
/// Initializes a new instance of the <see cref="SvgDocument"/> class.
/// </summary>
public SvgDocument()
{
Ppi = PointsPerInch;
}
public Uri BaseUri { get; set; }
/// <summary>
/// Gets an <see cref="SvgElementIdManager"/> for this document.
/// </summary>
protected internal virtual SvgElementIdManager IdManager
{
get
{
if (_idManager == null)
{
_idManager = new SvgElementIdManager(this);
}
return _idManager;
}
}
/// <summary>
/// Overwrites the current IdManager with a custom implementation.
/// Be careful with this: If elements have been inserted into the document before,
/// you have to take care that the new IdManager also knows of them.
/// </summary>
/// <param name="manager"></param>
public void OverwriteIdManager(SvgElementIdManager manager)
{
_idManager = manager;
}
/// <summary>
/// Gets or sets the Pixels Per Inch of the rendered image.
/// </summary>
public int Ppi { get; set; }
/// <summary>
/// Gets or sets an external Cascading Style Sheet (CSS)
/// </summary>
public string ExternalCSSHref { get; set; }
#region ITypeDescriptorContext Members
IContainer ITypeDescriptorContext.Container
{
get { throw new NotImplementedException(); }
}
object ITypeDescriptorContext.Instance
{
get { return this; }
}
void ITypeDescriptorContext.OnComponentChanged()
{
throw new NotImplementedException();
}
bool ITypeDescriptorContext.OnComponentChanging()
{
throw new NotImplementedException();
}
PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor
{
get { throw new NotImplementedException(); }
}
object IServiceProvider.GetService(Type serviceType)
{
throw new NotImplementedException();
}
#endregion
/// <summary>
/// Retrieves the <see cref="SvgElement"/> with the specified ID.
/// </summary>
/// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
/// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
public virtual SvgElement GetElementById(string id)
{
return IdManager.GetElementById(id);
}
/// <summary>
/// Retrieves the <see cref="SvgElement"/> with the specified ID.
/// </summary>
/// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
/// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
public virtual TSvgElement GetElementById<TSvgElement>(string id) where TSvgElement : SvgElement
{
return (this.GetElementById(id) as TSvgElement);
}
/// <summary>
/// Validate whether the system has GDI+ capabilities (non Windows related).
/// </summary>
/// <returns>Boolean whether the system is capable of using GDI+</returns>
public static bool SystemIsGdiPlusCapable()
{
try
{
EnsureSystemIsGdiPlusCapable();
}
catch (SvgGdiPlusCannotBeLoadedException)
{
return false;
}
catch (Exception)
{
//If somehow another type of exception is raised by the ensure function we will let it bubble up, since that might indicate other issues/problems
throw;
}
return true;
}
/// <summary>
/// Ensure that the running system is GDI capable, if not this will yield a
/// SvgGdiPlusCannotBeLoadedException exception.
/// </summary>
public static void EnsureSystemIsGdiPlusCapable()
{
try
{
using (var matrix = new Matrix(0f, 0f, 0f, 0f, 0f, 0f)) { }
}
// GDI+ loading errors will result in TypeInitializationExceptions,
// for readability we will catch and wrap the error
catch (Exception e)
{
if (ExceptionCaughtIsGdiPlusRelated(e))
{
// Throw only the customized exception if we are sure GDI+ is causing the problem
throw new SvgGdiPlusCannotBeLoadedException(e);
}
//If the Matrix creation is causing another type of exception we should just raise that one
throw;
}
}
/// <summary>
/// Check if the current exception or one of its children is the targeted GDI+ exception.
/// It can be hidden in one of the InnerExceptions, so we need to iterate over them.
/// </summary>
/// <param name="e">The exception to validate against the GDI+ check</param>
private static bool ExceptionCaughtIsGdiPlusRelated(Exception e)
{
var currE = e;
int cnt = 0; // Keep track of depth to prevent endless-loops
while (currE != null && cnt < 10)
{
var typeException = currE as DllNotFoundException;
if (typeException?.Message?.LastIndexOf("libgdiplus", StringComparison.OrdinalIgnoreCase) > -1)
{
return true;
}
currE = currE.InnerException;
cnt++;
}
return false;
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <param name="baseUri"> base uri for linked file</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static SvgDocument Open(string path, Uri baseUri = null)
{
return Open<SvgDocument>(path, null, baseUri == null ? new Uri(System.IO.Path.GetFullPath(path)) : baseUri);
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <param name="baseUri"> base uri for linked file</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static T Open<T>(string path, Uri baseUri = null) where T : SvgDocument, new()
{
return Open<T>(path, null, baseUri);
}
/// <summary>
/// Opens the document at the specified path and loads the SVG contents.
/// </summary>
/// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
/// <param name="baseUri"> base uri for linked file</param>
/// <param name="entities">A dictionary of custom entity definitions to be used when resolving XML entities within the document.</param>
/// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
/// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
public static T Open<T>(string path, Dictionary<string, string> entities, Uri baseUri = null) where T : SvgDocument, new()
{
if (string.IsNullOrEmpty(path))
{
throw new ArgumentNullException("path");
}
if (!File.Exists(path))
{
throw new FileNotFoundException("The specified document cannot be found.", path);
}
using (var stream = File.OpenRead(path))
{
var doc = Open<T>(stream, entities, baseUri == null ? new Uri(System.IO.Path.GetFullPath(path)) : baseUri);
if (baseUri == null)
doc.BaseUri = new Uri(System.IO.Path.GetFullPath(path));
else
doc.BaseUri = baseUri;
return doc;
}
}
/// <summary>
/// Attempts to open an SVG document from the specified <see cref="Stream"/>.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
/// <param name="baseUri"> base uri for linked file</param>
public static T Open<T>(Stream stream, Uri baseUri = null) where T : SvgDocument, new()
{
return Open<T>(stream, null, baseUri);
}
/// <summary>
/// Attempts to create an SVG document from the specified string data.
/// </summary>
/// <param name="svg">The SVG data.</param>
public static T FromSvg<T>(string svg) where T : SvgDocument, new()
{
if (string.IsNullOrEmpty(svg))
{
throw new ArgumentNullException("svg");
}
using (var strReader = new System.IO.StringReader(svg))
{
var reader = new SvgTextReader(strReader, null)
{
XmlResolver = new SvgDtdResolver(),
WhitespaceHandling = WhitespaceHandling.None
};
return Open<T>(reader);
}
}
/// <summary>
/// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
/// <param name="entities">Custom entity definitions.</param>
/// <param name="baseUri"> base uri for linked file</param>
/// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
public static T Open<T>(Stream stream, Dictionary<string, string> entities, Uri baseUri = null) where T : SvgDocument, new()
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
// Don't close the stream via a dispose: that is the client's job.
var reader = new SvgTextReader(stream, entities)
{
XmlResolver = new SvgDtdResolver(),
WhitespaceHandling = WhitespaceHandling.None
};
return Open<T>(reader, baseUri);
}
private static T Open<T>(XmlReader reader, Uri baseUri = null) where T : SvgDocument, new()
{
if (!SkipGdiPlusCapabilityCheck)
{
EnsureSystemIsGdiPlusCapable(); //Validate whether the GDI+ can be loaded, this will yield an exception if not
}
var elementStack = new Stack<SvgElement>();
bool elementEmpty;
SvgElement element = null;
SvgElement parent;
T svgDocument = null;
var elementFactory = new SvgElementFactory();
var styles = new List<ISvgNode>();
while (reader.Read())
{
try
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
// Does this element have a value or children
// (Must do this check here before we progress to another node)
elementEmpty = reader.IsEmptyElement;
// Create element
if (elementStack.Count > 0)
{
element = elementFactory.CreateElement(reader, svgDocument);
}
else
{
svgDocument = elementFactory.CreateDocument<T>(reader);
if (baseUri != null)
svgDocument.BaseUri = baseUri;
element = svgDocument;
}
// Add to the parents children
if (elementStack.Count > 0)
{
parent = elementStack.Peek();
if (parent != null && element != null)
{
parent.Children.Add(element);
parent.Nodes.Add(element);
}
}
// Push element into stack
elementStack.Push(element);
// Need to process if the element is empty
if (elementEmpty)
{
goto case XmlNodeType.EndElement;
}
break;
case XmlNodeType.EndElement:
// Pop the element out of the stack
element = elementStack.Pop();
if (element.Nodes.OfType<SvgContentNode>().Any())
{
element.Content = (from e in element.Nodes select e.Content).Aggregate((p, c) => p + c);
}
else
{
element.Nodes.Clear(); // No sense wasting the space where it isn't needed
}
var unknown = element as SvgUnknownElement;
if (unknown != null && unknown.ElementName == "style")
{
styles.Add(unknown);
}
else if (element is SvgLink)
{
var stylecontent = ((SvgLink)element).GetLinkContentAsText(SvgLink.RelativeValue.Stylesheet);
if (!string.IsNullOrEmpty(stylecontent))
{
var elem = new SvgUnknownElement("style");
elem.Content = stylecontent;
styles.Add(elem);
}
}
break;
case XmlNodeType.CDATA:
case XmlNodeType.Text:
element = elementStack.Peek();
element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
element = elementStack.Peek();
element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
break;
}
}
catch (Exception exc)
{
Trace.TraceError(exc.Message);
}
}
if (styles.Any())
{
var cssTotal = styles.Select((s) => s.Content).Aggregate((p, c) => p + Environment.NewLine + c);
var cssParser = new Parser();
var sheet = cssParser.Parse(cssTotal);
foreach (var rule in sheet.StyleRules)
{
try
{
var rootNode = new NonSvgElement();
rootNode.Children.Add(svgDocument);
var elemsToStyle = rootNode.QuerySelectorAll(rule.Selector.ToString(), elementFactory);
foreach (var elem in elemsToStyle)
{
foreach (var decl in rule.Declarations)
{
elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity());
}
}
}
catch (Exception ex)
{
Trace.TraceWarning(ex.Message);
}
}
}
svgDocument?.FlushStyles(true);
return svgDocument;
}
/// <summary>
/// Opens an SVG document from the specified <see cref="XmlDocument"/>.
/// </summary>
/// <param name="document">The <see cref="XmlDocument"/> containing the SVG document XML.</param>
/// <param name="baseUri"> base uri for linked file</param>
/// <exception cref="ArgumentNullException">The <paramref name="document"/> parameter cannot be <c>null</c>.</exception>
public static SvgDocument Open(XmlDocument document, Uri baseUri = null)
{
if (document == null)
{
throw new ArgumentNullException("document");
}
var reader = new SvgNodeReader(document.DocumentElement, null);
return Open<SvgDocument>(reader, baseUri);
}
public static Bitmap OpenAsBitmap(string path)
{
return null;
}
public static Bitmap OpenAsBitmap(XmlDocument document)
{
return null;
}
private void Draw(ISvgRenderer renderer, ISvgBoundable boundable)
{
renderer.SetBoundable(boundable);
this.Render(renderer);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
/// </summary>
/// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
/// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
public void Draw(ISvgRenderer renderer)
{
if (renderer == null)
{
throw new ArgumentNullException("renderer");
}
this.Draw(renderer, this);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics)
{
this.Draw(graphics, null);
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
/// </summary>
/// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
/// <param name="size">The <see cref="SizeF"/> to render the document. If <c>null</c> document is rendered at the default document size.</param>
/// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
public void Draw(Graphics graphics, SizeF? size)
{
if (graphics == null)
{
throw new ArgumentNullException("graphics");
}
using (var renderer = SvgRenderer.FromGraphics(graphics))
{
var boundable = size.HasValue ? (ISvgBoundable)new GenericBoundable(0, 0, size.Value.Width, size.Value.Height) : this;
this.Draw(renderer, boundable);
}
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> and returns the image as a <see cref="Bitmap"/>.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw()
{
//Trace.TraceInformation("Begin Render");
Bitmap bitmap = null;
try
{
try
{
var size = GetDimensions();
bitmap = new Bitmap((int)Math.Round(size.Width), (int)Math.Round(size.Height));
}
catch (ArgumentException e)
{
// When processing too many files at one the system can run out of memory
throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
}
//bitmap.SetResolution(300, 300);
this.Draw(bitmap);
}
catch
{
if (bitmap != null)
bitmap.Dispose();
throw;
}
//Trace.TraceInformation("End Render");
return bitmap;
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> into a given Bitmap <see cref="Bitmap"/>.
/// </summary>
public virtual void Draw(Bitmap bitmap)
{
//Trace.TraceInformation("Begin Render");
using (var renderer = SvgRenderer.FromImage(bitmap))
{
var boundable = new GenericBoundable(0, 0, bitmap.Width, bitmap.Height);
this.Draw(renderer, boundable);
}
//Trace.TraceInformation("End Render");
}
/// <summary>
/// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
/// If one of rasterWidth and rasterHeight is zero, the image is scaled preserving aspect ratio,
/// otherwise the aspect ratio is ignored.
/// </summary>
/// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
{
var imageSize = GetDimensions();
var bitmapSize = imageSize;
this.RasterizeDimensions(ref bitmapSize, rasterWidth, rasterHeight);
if (bitmapSize.Width == 0 || bitmapSize.Height == 0)
return null;
Bitmap bitmap = null;
try
{
try
{
bitmap = new Bitmap((int)Math.Round(bitmapSize.Width), (int)Math.Round(bitmapSize.Height));
}
catch (ArgumentException e)
{
// When processing too many files at one the system can run out of memory
throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
}
using (var renderer = SvgRenderer.FromImage(bitmap))
{
renderer.ScaleTransform(bitmapSize.Width / imageSize.Width, bitmapSize.Height / imageSize.Height);
var boundable = new GenericBoundable(0, 0, imageSize.Width, imageSize.Height);
this.Draw(renderer, boundable);
}
}
catch
{
if (bitmap != null)
bitmap.Dispose();
throw;
}
return bitmap;
}
/// <summary>
/// If both or one of raster height and width is not given (0), calculate that missing value from original SVG size
/// while keeping original SVG size ratio
/// </summary>
/// <param name="size"></param>
/// <param name="rasterWidth"></param>
/// <param name="rasterHeight"></param>
public virtual void RasterizeDimensions(ref SizeF size, int rasterWidth, int rasterHeight)
{
if (size == null || size.Width == 0)
return;
// Ratio of height/width of the original SVG size, to be used for scaling transformation
float ratio = size.Height / size.Width;
size.Width = rasterWidth > 0 ? (float)rasterWidth : size.Width;
size.Height = rasterHeight > 0 ? (float)rasterHeight : size.Height;
if (rasterHeight == 0 && rasterWidth > 0)
{
size.Height = (int)(rasterWidth * ratio);
}
else if (rasterHeight > 0 && rasterWidth == 0)
{
size.Width = (int)(rasterHeight / ratio);
}
}
public override void Write(XmlTextWriter writer)
{
//Save previous culture and switch to invariant for writing
var previousCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
base.Write(writer);
}
finally
{
// Make sure to set back the old culture even an error occurred.
//Switch culture back
Thread.CurrentThread.CurrentCulture = previousCulture;
}
}
public void Write(Stream stream, bool useBom = true)
{
var xmlWriter = new XmlTextWriter(stream, useBom ? Encoding.UTF8 : new UTF8Encoding(false))
{
Formatting = Formatting.Indented
};
xmlWriter.WriteStartDocument();
xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);
if (!String.IsNullOrEmpty(this.ExternalCSSHref))
xmlWriter.WriteProcessingInstruction("xml-stylesheet", String.Format("type=\"text/css\" href=\"{0}\"", this.ExternalCSSHref));
this.Write(xmlWriter);
xmlWriter.Flush();
}
public void Write(string path, bool useBom = true)
{
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
{
this.Write(fs, useBom);
}
}
protected override void WriteStartElement(XmlTextWriter writer)
{
base.WriteStartElement(writer);
foreach (var ns in SvgAttributeAttribute.Namespaces)
{
if (string.IsNullOrEmpty(ns.Key))
writer.WriteAttributeString("xmlns", ns.Value);
else
writer.WriteAttributeString("xmlns", ns.Key, null, ns.Value);
}
writer.WriteAttributeString("version", "1.1");
}
}
}