SvgDocument.cs 15.4 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;
davescriven's avatar
davescriven committed
12
13
14
15

namespace Svg
{
    /// <summary>
16
    /// The class used to create and load SVG documents.
davescriven's avatar
davescriven committed
17
18
19
    /// </summary>
    public class SvgDocument : SvgFragment, ITypeDescriptorContext
    {
20
        public static readonly int PointsPerInch = 96;
21
        private SvgElementIdManager _idManager;
22

23
24
25
        /// <summary>
        /// Initializes a new instance of the <see cref="SvgDocument"/> class.
        /// </summary>
26
        public SvgDocument()
davescriven's avatar
davescriven committed
27
        {
James Welle's avatar
James Welle committed
28
            Ppi = PointsPerInch;
davescriven's avatar
davescriven committed
29
30
31
32
33
34
35
36
37
        }

        /// <summary>
        /// Gets an <see cref="SvgElementIdManager"/> for this document.
        /// </summary>
        protected internal virtual SvgElementIdManager IdManager
        {
            get
            {
38
                if (_idManager == null)
39
                {
40
                    _idManager = new SvgElementIdManager(this);
41
                }
davescriven's avatar
davescriven committed
42

43
                return _idManager;
davescriven's avatar
davescriven committed
44
45
            }
        }
46
47
48
49
50
51
52
53
54
        
        /// <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
55
            _idManager = manager;
56
        }
davescriven's avatar
davescriven committed
57

58
59
60
        /// <summary>
        /// Gets or sets the Pixels Per Inch of the rendered image.
        /// </summary>
61
62
63
64
65
        public int Ppi { get; set; }

        #region ITypeDescriptorContext Members

        IContainer ITypeDescriptorContext.Container
davescriven's avatar
davescriven committed
66
        {
67
            get { throw new NotImplementedException(); }
davescriven's avatar
davescriven committed
68
69
        }

70
        object ITypeDescriptorContext.Instance
davescriven's avatar
davescriven committed
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
            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
105
106
        }

107
108
109
110
111
112
113
114
115
        /// <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);
        }
116
117
118
119
120
121
122
123
124
125
126
        
                /// <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>
        /// <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);
        }
127

davescriven's avatar
davescriven committed
128
        /// <summary>
129
        /// Opens the document at the specified path and loads the SVG contents.
davescriven's avatar
davescriven committed
130
131
132
133
        /// </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>
134
        public static T Open<T>(string path) where T : SvgDocument, new()
135
        {
136
            return Open<T>(path, null);
137
138
        }

139
        /// <summary>
140
        /// Opens the document at the specified path and loads the SVG contents.
141
142
143
144
        /// </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>
145
        /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
146
        public static T Open<T>(string path, Dictionary<string, string> entities) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
147
        {
148
149
150
151
152
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }

davescriven's avatar
davescriven committed
153
            if (!File.Exists(path))
154
            {
davescriven's avatar
davescriven committed
155
                throw new FileNotFoundException("The specified document cannot be found.", path);
156
            }
davescriven's avatar
davescriven committed
157

158
            return Open<T>(File.OpenRead(path), entities);
davescriven's avatar
davescriven committed
159
160
        }

161
162
163
164
        /// <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>
165
        public static T Open<T>(Stream stream) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
166
        {
167
            return Open<T>(stream, null);
davescriven's avatar
davescriven committed
168
169
        }

170
        /// <summary>
171
        /// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
172
173
174
        /// </summary>
        /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
        /// <param name="entities">Custom entity definitions.</param>
175
        /// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
176
        public static T Open<T>(Stream stream, Dictionary<string, string> entities) where T : SvgDocument, new()
davescriven's avatar
davescriven committed
177
        {
178
179
180
181
182
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

183
            //Trace.TraceInformation("Begin Read");
davescriven's avatar
davescriven committed
184

185
            using (var reader = new SvgTextReader(stream, entities))
davescriven's avatar
davescriven committed
186
            {
187
                var elementStack = new Stack<SvgElement>();
188
                bool elementEmpty;
davescriven's avatar
davescriven committed
189
                SvgElement element = null;
190
                SvgElement parent;
191
                T svgDocument = null;
davescriven's avatar
davescriven committed
192
193
194
195
196
197
198
199
200
201
202
203
                reader.XmlResolver = new SvgDtdResolver();
                reader.WhitespaceHandling = WhitespaceHandling.None;

                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)
204
                                elementEmpty = reader.IsEmptyElement;
davescriven's avatar
davescriven committed
205
206
                                // Create element
                                if (elementStack.Count > 0)
207
                                {
davescriven's avatar
davescriven committed
208
                                    element = SvgElementFactory.CreateElement(reader, svgDocument);
209
                                }
davescriven's avatar
davescriven committed
210
211
                                else
                                {
212
213
                                    svgDocument = SvgElementFactory.CreateDocument<T>(reader);
                                    element = svgDocument;
davescriven's avatar
davescriven committed
214
215
216
217
218
219
                                }

                                // Add to the parents children
                                if (elementStack.Count > 0)
                                {
                                    parent = elementStack.Peek();
220
                                    if (parent != null && element != null)
221
                                    {
222
                                        parent.Children.Add(element);
223
224
                                        parent.Nodes.Add(element);
                                    }
davescriven's avatar
davescriven committed
225
226
227
228
229
230
                                }

                                // Push element into stack
                                elementStack.Push(element);

                                // Need to process if the element is empty
231
                                if (elementEmpty)
232
                                {
davescriven's avatar
davescriven committed
233
                                    goto case XmlNodeType.EndElement;
234
                                }
davescriven's avatar
davescriven committed
235
236
237

                                break;
                            case XmlNodeType.EndElement:
tebjan's avatar
tebjan committed
238

davescriven's avatar
davescriven committed
239
240
241
                                // Pop the element out of the stack
                                element = elementStack.Pop();

242
                                if (element.Nodes.OfType<SvgContentNode>().Any())
davescriven's avatar
davescriven committed
243
                                {
244
245
246
247
248
                                    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
davescriven's avatar
davescriven committed
249
250
251
252
                                }
                                break;
                            case XmlNodeType.CDATA:
                            case XmlNodeType.Text:
253
254
                                element = elementStack.Peek();
                                element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
davescriven's avatar
davescriven committed
255
                                break;
256
257
                            case XmlNodeType.EntityReference:
                                reader.ResolveEntity();
258
259
                                element = elementStack.Peek();
                                element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
260
                                break;
davescriven's avatar
davescriven committed
261
262
263
264
265
266
267
268
                        }
                    }
                    catch (Exception exc)
                    {
                        Trace.TraceError(exc.Message);
                    }
                }

269
                //Trace.TraceInformation("End Read");
davescriven's avatar
davescriven committed
270
271
272
273
                return svgDocument;
            }
        }

274
275
276
277
278
        /// <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>
279
        public static SvgDocument Open(XmlDocument document)
davescriven's avatar
davescriven committed
280
        {
281
282
283
284
285
            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

Eric Domke's avatar
Eric Domke committed
286
287
288
289
            using (var stream = new MemoryStream(UTF8Encoding.Default.GetBytes(document.InnerXml)))
            {
                return Open<SvgDocument>(stream, null);
            }
davescriven's avatar
davescriven committed
290
291
292
293
294
295
296
        }

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

297
        public static Bitmap OpenAsBitmap(XmlDocument document)
davescriven's avatar
davescriven committed
298
299
300
301
        {
            return null;
        }

302
303
304
305
        /// <summary>
        /// Renders the <see cref="SvgDocument"/> to the specified <see cref="SvgRenderer"/>.
        /// </summary>
        /// <param name="renderer">The <see cref="SvgRenderer"/> to render the document with.</param>
306
        /// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
307
        public void Draw(SvgRenderer renderer)
davescriven's avatar
davescriven committed
308
        {
309
310
311
312
313
            if (renderer == null)
            {
                throw new ArgumentNullException("renderer");
            }

314
            this.Render(renderer);
davescriven's avatar
davescriven committed
315
316
        }

317
318
319
320
321
322
323
324
325
326
327
328
        /// <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)
        {
            if (graphics == null)
            {
                throw new ArgumentNullException("graphics");
            }

329
            this.Render(SvgRenderer.FromGraphics(graphics));
330
331
        }

332
333
334
335
        /// <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>
davescriven's avatar
davescriven committed
336
337
        public virtual Bitmap Draw()
        {
338
            //Trace.TraceInformation("Begin Render");
davescriven's avatar
davescriven committed
339

340
            var size = GetDimensions();
341
            var bitmap = new Bitmap((int)Math.Ceiling(size.Width), (int)Math.Ceiling(size.Height));
342
       // 	bitmap.SetResolution(300, 300);
Tebjan Halm's avatar
Tebjan Halm committed
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
            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");

364
            try
davescriven's avatar
davescriven committed
365
            {
366
                using (var renderer = SvgRenderer.FromImage(bitmap))
367
                {
368
369
370
371
372
                    renderer.TextRenderingHint = TextRenderingHint.AntiAlias;
                    renderer.TextContrast = 1;
                    renderer.PixelOffsetMode = PixelOffsetMode.Half;
                    this.Render(renderer);
                    renderer.Save();
373
374
375
376
377
                }
            }
            catch
            {
                throw;
davescriven's avatar
davescriven committed
378
379
            }

380
            //Trace.TraceInformation("End Render");
davescriven's avatar
davescriven committed
381
382
383
384
        }

        public void Write(Stream stream)
        {
Tebjan Halm's avatar
Tebjan Halm committed
385
386
387

            var xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
            xmlWriter.Formatting = Formatting.Indented;
388

Tebjan Halm's avatar
Tebjan Halm committed
389
390
391
392
            xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);

            this.WriteElement(xmlWriter);

Tebjan Halm's avatar
Tebjan Halm committed
393
            xmlWriter.Flush();
davescriven's avatar
davescriven committed
394
395
396
397
        }

        public void Write(string path)
        {
Tebjan Halm's avatar
Tebjan Halm committed
398
399
400
401
            using(var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                this.Write(fs);
            }
davescriven's avatar
davescriven committed
402
403
        }
    }
Eric Domke's avatar
Eric Domke committed
404
}