SvgExtentions.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Xml;
  8. using System.Threading;
  9. using System.Globalization;
  10. #pragma warning disable
  11. namespace Svg
  12. {
  13. /// <summary>
  14. /// Svg helpers
  15. /// </summary>
  16. public static class SvgExtentions
  17. {
  18. public static void SetRectangle(this SvgRectangle r, RectangleF bounds)
  19. {
  20. r.X = bounds.X;
  21. r.Y = bounds.Y;
  22. r.Width = bounds.Width;
  23. r.Height = bounds.Height;
  24. }
  25. public static RectangleF GetRectangle(this SvgRectangle r)
  26. {
  27. return new RectangleF(r.X, r.Y, r.Width, r.Height);
  28. }
  29. public static string GetXML(this SvgDocument doc)
  30. {
  31. var ret = "";
  32. using (var ms = new MemoryStream())
  33. {
  34. doc.Write(ms);
  35. ms.Position = 0;
  36. var sr = new StreamReader(ms);
  37. ret = sr.ReadToEnd();
  38. sr.Close();
  39. }
  40. return ret;
  41. }
  42. public static string GetXML(this SvgElement elem)
  43. {
  44. var result = "";
  45. var currentCulture = Thread.CurrentThread.CurrentCulture;
  46. try
  47. {
  48. Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  49. using (StringWriter str = new StringWriter())
  50. {
  51. using (XmlTextWriter xml = new XmlTextWriter(str))
  52. {
  53. elem.Write(xml);
  54. result = str.ToString();
  55. }
  56. }
  57. }
  58. finally
  59. {
  60. // Make sure to set back the old culture even an error occurred.
  61. Thread.CurrentThread.CurrentCulture = currentCulture;
  62. }
  63. return result;
  64. }
  65. public static bool HasNonEmptyCustomAttribute(this SvgElement element, string name)
  66. {
  67. return element.CustomAttributes.ContainsKey(name) && !string.IsNullOrEmpty(element.CustomAttributes[name]);
  68. }
  69. public static void ApplyRecursive(this SvgElement elem, Action<SvgElement> action)
  70. {
  71. action(elem);
  72. if (!(elem is SvgDocument)) //don't apply action to subtree of documents
  73. {
  74. foreach (var element in elem.Children)
  75. {
  76. element.ApplyRecursive(action);
  77. }
  78. }
  79. }
  80. public static void ApplyRecursiveDepthFirst(this SvgElement elem, Action<SvgElement> action)
  81. {
  82. if (!(elem is SvgDocument)) //don't apply action to subtree of documents
  83. {
  84. foreach (var element in elem.Children)
  85. {
  86. element.ApplyRecursiveDepthFirst(action);
  87. }
  88. }
  89. action(elem);
  90. }
  91. }
  92. }
  93. #pragma warning restore