SvgDocument.cs 24.1 KB
Newer Older
davescriven's avatar
davescriven committed
1
2
3
4
5
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
6
7
using System.Drawing.Drawing2D;
using System.Drawing.Text;
davescriven's avatar
davescriven committed
8
9
10
using System.IO;
using System.Text;
using System.Xml;
11
using System.Linq;
Matt Schneeberger's avatar
Matt Schneeberger committed
12
using Svg.ExCSS;
Eric Domke's avatar
Eric Domke committed
13
using Svg.Css;
14
15
using System.Threading;
using System.Globalization;
16
using Svg.Exceptions;
17
using System.Runtime.InteropServices;
davescriven's avatar
davescriven committed
18
19
20
21

namespace Svg
{
    /// <summary>
22
    /// The class used to create and load SVG documents.
davescriven's avatar
davescriven committed
23
24
25
    /// </summary>
    public class SvgDocument : SvgFragment, ITypeDescriptorContext
    {
26
        public static readonly int PointsPerInch = GetSystemDpi();
27
        private SvgElementIdManager _idManager;
28

Eric Domke's avatar
Eric Domke committed
29
        private Dictionary<string, IEnumerable<SvgFontFace>> _fontDefns = null;
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

        private static int GetSystemDpi()
        {
            IntPtr hDC = GetDC(IntPtr.Zero);
            const int LOGPIXELSY = 90;
            int result = GetDeviceCaps(hDC, LOGPIXELSY);
            ReleaseDC(IntPtr.Zero, hDC);
            return result;
        }

        [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);

Eric Domke's avatar
Eric Domke committed
49
50
51
52
53
54
55
56
57
58
59
        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;
        }

60
61
62
        /// <summary>
        /// Initializes a new instance of the <see cref="SvgDocument"/> class.
        /// </summary>
63
        public SvgDocument()
davescriven's avatar
davescriven committed
64
        {
James Welle's avatar
James Welle committed
65
            Ppi = PointsPerInch;
davescriven's avatar
davescriven committed
66
67
        }

68
69
        public Uri BaseUri { get; set; }

davescriven's avatar
davescriven committed
70
71
72
73
74
75
76
        /// <summary>
        /// Gets an <see cref="SvgElementIdManager"/> for this document.
        /// </summary>
        protected internal virtual SvgElementIdManager IdManager
        {
            get
            {
77
                if (_idManager == null)
78
                {
79
                    _idManager = new SvgElementIdManager(this);
80
                }
davescriven's avatar
davescriven committed
81

82
                return _idManager;
davescriven's avatar
davescriven committed
83
84
            }
        }
Eric Domke's avatar
Eric Domke committed
85

86
87
88
89
90
91
92
93
        /// <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)
        {
James Welle's avatar
James Welle committed
94
            _idManager = manager;
95
        }
davescriven's avatar
davescriven committed
96

97
98
99
        /// <summary>
        /// Gets or sets the Pixels Per Inch of the rendered image.
        /// </summary>
100
        public int Ppi { get; set; }
sschurig's avatar
sschurig committed
101
102
103
104
105
        
        /// <summary>
        /// Gets or sets an external Cascading Style Sheet (CSS)
        /// </summary>
        public string ExternalCSSHref { get; set; }        
106
107
108
109

        #region ITypeDescriptorContext Members

        IContainer ITypeDescriptorContext.Container
davescriven's avatar
davescriven committed
110
        {
111
            get { throw new NotImplementedException(); }
davescriven's avatar
davescriven committed
112
113
        }

114
        object ITypeDescriptorContext.Instance
davescriven's avatar
davescriven committed
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
            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);
davescriven's avatar
davescriven committed
149
150
        }

151
152
153
154
155
156
157
158
159
        /// <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);
        }
Eric Domke's avatar
Eric Domke committed
160
161

        /// <summary>
162
163
164
165
166
167
168
169
170
        /// 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>
        /// <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)
        {
            return Open<SvgDocument>(path, null);
        }
171

davescriven's avatar
davescriven committed
172
        /// <summary>
173
        /// Opens the document at the specified path and loads the SVG contents.
davescriven's avatar
davescriven committed
174
175
176
177
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing the path of the file to open.</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>
178
        public static T Open<T>(string path) where T : SvgDocument, new()
179
        {
180
            return Open<T>(path, null);
181
182
        }

183
        /// <summary>
184
        /// Opens the document at the specified path and loads the SVG contents.
185
186
187
188
        /// </summary>
        /// <param name="path">A <see cref="string"/> containing the path of the file to open.</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>
189
        /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
190
        public static T Open<T>(string path, Dictionary<string, string> entities) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
191
        {
192
193
194
195
196
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

davescriven's avatar
davescriven committed
197
            if (!File.Exists(path))
198
            {
davescriven's avatar
davescriven committed
199
                throw new FileNotFoundException("The specified document cannot be found.", path);
200
            }
davescriven's avatar
davescriven committed
201

Eric Domke's avatar
Eric Domke committed
202
203
204
205
206
207
            using (var stream = File.OpenRead(path))
            {
                var doc = Open<T>(stream, entities);
                doc.BaseUri = new Uri(System.IO.Path.GetFullPath(path));
                return doc;
            }
davescriven's avatar
davescriven committed
208
209
        }

210
211
212
213
        /// <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>
214
        public static T Open<T>(Stream stream) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
215
        {
216
            return Open<T>(stream, null);
davescriven's avatar
davescriven committed
217
218
        }

Eric Domke's avatar
Eric Domke committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239

        /// <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);
                reader.XmlResolver = new SvgDtdResolver();
                reader.WhitespaceHandling = WhitespaceHandling.None;
                return Open<T>(reader);
            }
        }

240
        /// <summary>
241
        /// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
242
243
244
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
        /// <param name="entities">Custom entity definitions.</param>
245
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
246
        public static T Open<T>(Stream stream, Dictionary<string, string> entities) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
247
        {
248
249
250
251
252
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

Eric Domke's avatar
Eric Domke committed
253
254
255
256
257
258
            // Don't close the stream via a dispose: that is the client's job.
            var reader = new SvgTextReader(stream, entities);
            reader.XmlResolver = new SvgDtdResolver();
            reader.WhitespaceHandling = WhitespaceHandling.None;
            return Open<T>(reader);
        }
davescriven's avatar
davescriven committed
259

Eric Domke's avatar
Eric Domke committed
260
261
262
263
264
265
266
        private static T Open<T>(XmlReader reader) where T : SvgDocument, new()
        {
            var elementStack = new Stack<SvgElement>();
            bool elementEmpty;
            SvgElement element = null;
            SvgElement parent;
            T svgDocument = null;
267
268
			var elementFactory = new SvgElementFactory();

Eric Domke's avatar
Eric Domke committed
269
270
271
            var styles = new List<ISvgNode>();

            while (reader.Read())
davescriven's avatar
davescriven committed
272
            {
Eric Domke's avatar
Eric Domke committed
273
                try
davescriven's avatar
davescriven committed
274
                {
Eric Domke's avatar
Eric Domke committed
275
                    switch (reader.NodeType)
davescriven's avatar
davescriven committed
276
                    {
Eric Domke's avatar
Eric Domke committed
277
278
279
280
281
282
283
                        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)
                            {
284
                                element = elementFactory.CreateElement(reader, svgDocument);
Eric Domke's avatar
Eric Domke committed
285
286
287
                            }
                            else
                            {
288
                                svgDocument = elementFactory.CreateDocument<T>(reader);
Eric Domke's avatar
Eric Domke committed
289
290
291
292
293
294
295
296
                                element = svgDocument;
                            }

                            // Add to the parents children
                            if (elementStack.Count > 0)
                            {
                                parent = elementStack.Peek();
                                if (parent != null && element != null)
davescriven's avatar
davescriven committed
297
                                {
Eric Domke's avatar
Eric Domke committed
298
299
                                    parent.Children.Add(element);
                                    parent.Nodes.Add(element);
davescriven's avatar
davescriven committed
300
                                }
Eric Domke's avatar
Eric Domke committed
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
                            }

                            // 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);
                            }
                            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);
                }
            }
davescriven's avatar
davescriven committed
350

Eric Domke's avatar
Eric Domke committed
351
352
353
354
355
            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);
356
357
                AggregateSelectorList aggList;
                IEnumerable<BaseSelector> selectors;
Eric Domke's avatar
Eric Domke committed
358
                IEnumerable<SvgElement> elemsToStyle;
davescriven's avatar
davescriven committed
359

Eric Domke's avatar
Eric Domke committed
360
361
                foreach (var rule in sheet.StyleRules)
                {
362
363
364
365
366
367
368
369
370
371
372
                    aggList = rule.Selector as AggregateSelectorList;
                    if (aggList != null && aggList.Delimiter == ",")
                    {
                        selectors = aggList;
                    }
                    else
                    {
                        selectors = Enumerable.Repeat(rule.Selector, 1);
                    }

                    foreach (var selector in selectors)
davescriven's avatar
davescriven committed
373
                    {
374
                        elemsToStyle = svgDocument.QuerySelectorAll(rule.Selector.ToString(), elementFactory);
375
                        foreach (var elem in elemsToStyle)
Eric Domke's avatar
Eric Domke committed
376
                        {
377
378
379
380
                            foreach (var decl in rule.Declarations)
                            {
                                elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity());
                            }
Eric Domke's avatar
Eric Domke committed
381
                        }
davescriven's avatar
davescriven committed
382
383
                    }
                }
Eric Domke's avatar
Eric Domke committed
384
385
            }

386
            if (svgDocument != null) FlushStyles(svgDocument);
Eric Domke's avatar
Eric Domke committed
387
388
            return svgDocument;
        }
davescriven's avatar
davescriven committed
389

Eric Domke's avatar
Eric Domke committed
390
391
392
393
394
395
        private static void FlushStyles(SvgElement elem)
        {
            elem.FlushStyles();
            foreach (var child in elem.Children)
            {
                FlushStyles(child);
davescriven's avatar
davescriven committed
396
397
398
            }
        }

399
400
401
402
403
        /// <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>
        /// <exception cref="ArgumentNullException">The <paramref name="document"/> parameter cannot be <c>null</c>.</exception>
404
        public static SvgDocument Open(XmlDocument document)
davescriven's avatar
davescriven committed
405
        {
406
407
408
409
410
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

411
412
            var reader = new SvgNodeReader(document.DocumentElement, null);
            return Open<SvgDocument>(reader);
davescriven's avatar
davescriven committed
413
414
415
416
417
418
419
        }

        public static Bitmap OpenAsBitmap(string path)
        {
            return null;
        }

420
        public static Bitmap OpenAsBitmap(XmlDocument document)
davescriven's avatar
davescriven committed
421
422
423
424
        {
            return null;
        }

425
        /// <summary>
Eric Domke's avatar
Eric Domke committed
426
        /// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
427
        /// </summary>
Eric Domke's avatar
Eric Domke committed
428
        /// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
429
        /// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
Eric Domke's avatar
Eric Domke committed
430
        public void Draw(ISvgRenderer renderer)
davescriven's avatar
davescriven committed
431
        {
432
433
434
435
436
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

Eric Domke's avatar
Eric Domke committed
437
            renderer.SetBoundable(this);
438
            this.Render(renderer);
davescriven's avatar
davescriven committed
439
440
        }

441
442
443
444
445
446
447
448
449
450
        /// <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)
        {
            Draw(graphics, null);
        }

451
452
453
454
        /// <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>
455
        /// <param name="size">The <see cref="SizeF"/> to render the document. If <c>null</c> document is rendered at the default document size.</param>
456
        /// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
457
        public void Draw(Graphics graphics, SizeF? size)
458
459
460
461
462
463
        {
            if (graphics == null)
            {
                throw new ArgumentNullException("graphics");
            }

464
            var renderer = SvgRenderer.FromGraphics(graphics);
465
466
467
468
469
470
471
472
            if (size.HasValue)
            {
                renderer.SetBoundable(new GenericBoundable(0, 0, size.Value.Width, size.Value.Height));
            }
            else
            {
                renderer.SetBoundable(this);
            }
473
            this.Render(renderer);
474
475
        }

476
477
478
479
480
	    /// <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()
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
	    {
		    //Trace.TraceInformation("Begin Render");

		    var size = GetDimensions();
		    Bitmap bitmap = null;
		    try
		    {
			    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);
Tebjan Halm's avatar
Tebjan Halm committed
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
            try
            {
                Draw(bitmap);
            }
            catch
            {
                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");

518
            try
davescriven's avatar
davescriven committed
519
            {
520
521
522
523
				using (var renderer = SvgRenderer.FromImage(bitmap))
				{
					renderer.SetBoundable(new GenericBoundable(0, 0, bitmap.Width, bitmap.Height));

524
					//EO, 2014-12-05: Requested to ensure proper zooming out (reduce size). Otherwise it clip the image.
525
					this.Overflow = SvgOverflow.Auto;
526
527
528

					this.Render(renderer);
				}
529
530
531
532
            }
            catch
            {
                throw;
davescriven's avatar
davescriven committed
533
534
            }

535
            //Trace.TraceInformation("End Render");
davescriven's avatar
davescriven committed
536
537
        }

538
539
        /// <summary>
        /// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
540
541
        /// If one of rasterWidth and rasterHeight is zero, the image is scaled preserving aspect ratio,
        /// otherwise the aspect ratio is ignored.
542
543
544
545
        /// </summary>
        /// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
        public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
        {
546
547
548
            var imageSize = GetDimensions();
            var bitmapSize = imageSize;
            RasterizeDimensions(ref bitmapSize, rasterWidth, rasterHeight);
549

550
551
            if (bitmapSize.Width == 0 || bitmapSize.Height == 0)
                return null;
552

553
554
555
556
557
558
559
560
561
562
563
564
565
566
            var bitmap = new Bitmap((int)Math.Round(bitmapSize.Width), (int)Math.Round(bitmapSize.Height));
            try
            {
                var renderer = SvgRenderer.FromImage(bitmap);
                renderer.ScaleTransform(bitmapSize.Width / imageSize.Width, bitmapSize.Height / imageSize.Height);
                Draw(renderer);
            }
            catch
            {
                bitmap.Dispose();
                throw;
            }

            return bitmap;
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
        }

        /// <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);
          }
        }

597
598
599
600
        public override void Write(XmlTextWriter writer)
        {
            //Save previous culture and switch to invariant for writing
            var previousCulture = Thread.CurrentThread.CurrentCulture;
601
602
603
604
605
606
607
608
609
610
            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;
            }
611
612
        }

Vogelbacher Andreas's avatar
Vogelbacher Andreas committed
613
        public void Write(Stream stream, bool useBom = true)
davescriven's avatar
davescriven committed
614
        {
Tebjan Halm's avatar
Tebjan Halm committed
615

Vogelbacher Andreas's avatar
Vogelbacher Andreas committed
616
            var xmlWriter = new XmlTextWriter(stream, useBom ? Encoding.UTF8 : new System.Text.UTF8Encoding(false));
Tebjan Halm's avatar
Tebjan Halm committed
617
            xmlWriter.Formatting = Formatting.Indented;
Vogelbacher Andreas's avatar
Vogelbacher Andreas committed
618
            xmlWriter.WriteStartDocument();
Tebjan Halm's avatar
Tebjan Halm committed
619
            xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);
sschurig's avatar
sschurig committed
620
621
622
            
            if (!String.IsNullOrEmpty(this.ExternalCSSHref))
                xmlWriter.WriteProcessingInstruction("xml-stylesheet", String.Format("type=\"text/css\" href=\"{0}\"", this.ExternalCSSHref));
Tebjan Halm's avatar
Tebjan Halm committed
623

624
            this.Write(xmlWriter);
Tebjan Halm's avatar
Tebjan Halm committed
625

Tebjan Halm's avatar
Tebjan Halm committed
626
            xmlWriter.Flush();
davescriven's avatar
davescriven committed
627
628
        }

Vogelbacher Andreas's avatar
Vogelbacher Andreas committed
629
        public void Write(string path, bool useBom = true)
davescriven's avatar
davescriven committed
630
        {
Eric Domke's avatar
Eric Domke committed
631
            using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
Tebjan Halm's avatar
Tebjan Halm committed
632
            {
Vogelbacher Andreas's avatar
Vogelbacher Andreas committed
633
                this.Write(fs, useBom);
Tebjan Halm's avatar
Tebjan Halm committed
634
            }
davescriven's avatar
davescriven committed
635
636
        }
    }
sschurig's avatar
sschurig committed
637
}