SvgDocument.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.Drawing.Drawing2D;
  7. using System.Drawing.Text;
  8. using System.IO;
  9. using System.Text;
  10. using System.Xml;
  11. using System.Linq;
  12. using ExCSS;
  13. using Svg.Css;
  14. using System.Threading;
  15. using System.Globalization;
  16. using Svg.Exceptions;
  17. #pragma warning disable
  18. namespace Svg
  19. {
  20. /// <summary>
  21. /// The class used to create and load SVG documents.
  22. /// </summary>
  23. public class SvgDocument : SvgFragment, ITypeDescriptorContext
  24. {
  25. public static readonly int PointsPerInch = 96;
  26. private SvgElementIdManager _idManager;
  27. private Dictionary<string, IEnumerable<SvgFontFace>> _fontDefns = null;
  28. internal Dictionary<string, IEnumerable<SvgFontFace>> FontDefns()
  29. {
  30. if (_fontDefns == null)
  31. {
  32. _fontDefns = (from f in Descendants().OfType<SvgFontFace>()
  33. group f by f.FontFamily into family
  34. select family).ToDictionary(f => f.Key, f => (IEnumerable<SvgFontFace>)f);
  35. }
  36. return _fontDefns;
  37. }
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="SvgDocument"/> class.
  40. /// </summary>
  41. public SvgDocument()
  42. {
  43. Ppi = PointsPerInch;
  44. }
  45. public Uri BaseUri { get; set; }
  46. /// <summary>
  47. /// Gets an <see cref="SvgElementIdManager"/> for this document.
  48. /// </summary>
  49. protected internal virtual SvgElementIdManager IdManager
  50. {
  51. get
  52. {
  53. if (_idManager == null)
  54. {
  55. _idManager = new SvgElementIdManager(this);
  56. }
  57. return _idManager;
  58. }
  59. }
  60. /// <summary>
  61. /// Overwrites the current IdManager with a custom implementation.
  62. /// Be careful with this: If elements have been inserted into the document before,
  63. /// you have to take care that the new IdManager also knows of them.
  64. /// </summary>
  65. /// <param name="manager"></param>
  66. public void OverwriteIdManager(SvgElementIdManager manager)
  67. {
  68. _idManager = manager;
  69. }
  70. /// <summary>
  71. /// Gets or sets the Pixels Per Inch of the rendered image.
  72. /// </summary>
  73. public int Ppi { get; set; }
  74. /// <summary>
  75. /// Gets or sets an external Cascading Style Sheet (CSS)
  76. /// </summary>
  77. public string ExternalCSSHref { get; set; }
  78. #region ITypeDescriptorContext Members
  79. IContainer ITypeDescriptorContext.Container
  80. {
  81. get { throw new NotImplementedException(); }
  82. }
  83. object ITypeDescriptorContext.Instance
  84. {
  85. get { return this; }
  86. }
  87. void ITypeDescriptorContext.OnComponentChanged()
  88. {
  89. throw new NotImplementedException();
  90. }
  91. bool ITypeDescriptorContext.OnComponentChanging()
  92. {
  93. throw new NotImplementedException();
  94. }
  95. PropertyDescriptor ITypeDescriptorContext.PropertyDescriptor
  96. {
  97. get { throw new NotImplementedException(); }
  98. }
  99. object IServiceProvider.GetService(Type serviceType)
  100. {
  101. throw new NotImplementedException();
  102. }
  103. #endregion
  104. /// <summary>
  105. /// Retrieves the <see cref="SvgElement"/> with the specified ID.
  106. /// </summary>
  107. /// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
  108. /// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
  109. public virtual SvgElement GetElementById(string id)
  110. {
  111. return IdManager.GetElementById(id);
  112. }
  113. /// <summary>
  114. /// Retrieves the <see cref="SvgElement"/> with the specified ID.
  115. /// </summary>
  116. /// <param name="id">A <see cref="string"/> containing the ID of the element to find.</param>
  117. /// <returns>An <see cref="SvgElement"/> of one exists with the specified ID; otherwise false.</returns>
  118. public virtual TSvgElement GetElementById<TSvgElement>(string id) where TSvgElement : SvgElement
  119. {
  120. return (this.GetElementById(id) as TSvgElement);
  121. }
  122. /// <summary>
  123. /// Opens the document at the specified path and loads the SVG contents.
  124. /// </summary>
  125. /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
  126. /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
  127. /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
  128. public static SvgDocument Open(string path)
  129. {
  130. return Open<SvgDocument>(path, null);
  131. }
  132. /// <summary>
  133. /// Opens the document at the specified path and loads the SVG contents.
  134. /// </summary>
  135. /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
  136. /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
  137. /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
  138. public static T Open<T>(string path) where T : SvgDocument, new()
  139. {
  140. return Open<T>(path, null);
  141. }
  142. /// <summary>
  143. /// Opens the document at the specified path and loads the SVG contents.
  144. /// </summary>
  145. /// <param name="path">A <see cref="string"/> containing the path of the file to open.</param>
  146. /// <param name="entities">A dictionary of custom entity definitions to be used when resolving XML entities within the document.</param>
  147. /// <returns>An <see cref="SvgDocument"/> with the contents loaded.</returns>
  148. /// <exception cref="FileNotFoundException">The document at the specified <paramref name="path"/> cannot be found.</exception>
  149. public static T Open<T>(string path, Dictionary<string, string> entities) where T : SvgDocument, new()
  150. {
  151. if (string.IsNullOrEmpty(path))
  152. {
  153. throw new ArgumentNullException("path");
  154. }
  155. if (!File.Exists(path))
  156. {
  157. throw new FileNotFoundException("The specified document cannot be found.", path);
  158. }
  159. using (var stream = File.OpenRead(path))
  160. {
  161. var doc = Open<T>(stream, entities);
  162. doc.BaseUri = new Uri(System.IO.Path.GetFullPath(path));
  163. return doc;
  164. }
  165. }
  166. /// <summary>
  167. /// Attempts to open an SVG document from the specified <see cref="Stream"/>.
  168. /// </summary>
  169. /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
  170. public static T Open<T>(Stream stream) where T : SvgDocument, new()
  171. {
  172. return Open<T>(stream, null);
  173. }
  174. /// <summary>
  175. /// Attempts to create an SVG document from the specified string data.
  176. /// </summary>
  177. /// <param name="svg">The SVG data.</param>
  178. public static T FromSvg<T>(string svg) where T : SvgDocument, new()
  179. {
  180. if (string.IsNullOrEmpty(svg))
  181. {
  182. throw new ArgumentNullException("svg");
  183. }
  184. using (var strReader = new System.IO.StringReader(svg))
  185. {
  186. var reader = new SvgTextReader(strReader, null);
  187. reader.XmlResolver = new SvgDtdResolver();
  188. reader.WhitespaceHandling = WhitespaceHandling.None;
  189. return Open<T>(reader);
  190. }
  191. }
  192. /// <summary>
  193. /// Opens an SVG document from the specified <see cref="Stream"/> and adds the specified entities.
  194. /// </summary>
  195. /// <param name="stream">The <see cref="Stream"/> containing the SVG document to open.</param>
  196. /// <param name="entities">Custom entity definitions.</param>
  197. /// <exception cref="ArgumentNullException">The <paramref name="stream"/> parameter cannot be <c>null</c>.</exception>
  198. public static T Open<T>(Stream stream, Dictionary<string, string> entities) where T : SvgDocument, new()
  199. {
  200. if (stream == null)
  201. {
  202. throw new ArgumentNullException("stream");
  203. }
  204. // Don't close the stream via a dispose: that is the client's job.
  205. var reader = new SvgTextReader(stream, entities);
  206. reader.XmlResolver = new SvgDtdResolver();
  207. reader.WhitespaceHandling = WhitespaceHandling.None;
  208. return Open<T>(reader);
  209. }
  210. private static T Open<T>(XmlReader reader) where T : SvgDocument, new()
  211. {
  212. var elementStack = new Stack<SvgElement>();
  213. bool elementEmpty;
  214. SvgElement element = null;
  215. SvgElement parent;
  216. T svgDocument = null;
  217. var elementFactory = new SvgElementFactory();
  218. var styles = new List<ISvgNode>();
  219. while (reader.Read())
  220. {
  221. try
  222. {
  223. switch (reader.NodeType)
  224. {
  225. case XmlNodeType.Element:
  226. // Does this element have a value or children
  227. // (Must do this check here before we progress to another node)
  228. elementEmpty = reader.IsEmptyElement;
  229. // Create element
  230. if (elementStack.Count > 0)
  231. {
  232. element = elementFactory.CreateElement(reader, svgDocument);
  233. }
  234. else
  235. {
  236. svgDocument = elementFactory.CreateDocument<T>(reader);
  237. element = svgDocument;
  238. }
  239. // Add to the parents children
  240. if (elementStack.Count > 0)
  241. {
  242. parent = elementStack.Peek();
  243. if (parent != null && element != null)
  244. {
  245. parent.Children.Add(element);
  246. parent.Nodes.Add(element);
  247. }
  248. }
  249. // Push element into stack
  250. elementStack.Push(element);
  251. // Need to process if the element is empty
  252. if (elementEmpty)
  253. {
  254. goto case XmlNodeType.EndElement;
  255. }
  256. break;
  257. case XmlNodeType.EndElement:
  258. // Pop the element out of the stack
  259. element = elementStack.Pop();
  260. if (element.Nodes.OfType<SvgContentNode>().Any())
  261. {
  262. element.Content = (from e in element.Nodes select e.Content).Aggregate((p, c) => p + c);
  263. }
  264. else
  265. {
  266. element.Nodes.Clear(); // No sense wasting the space where it isn't needed
  267. }
  268. var unknown = element as SvgUnknownElement;
  269. if (unknown != null && unknown.ElementName == "style")
  270. {
  271. styles.Add(unknown);
  272. }
  273. break;
  274. case XmlNodeType.CDATA:
  275. case XmlNodeType.Text:
  276. element = elementStack.Peek();
  277. element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
  278. break;
  279. case XmlNodeType.EntityReference:
  280. reader.ResolveEntity();
  281. element = elementStack.Peek();
  282. element.Nodes.Add(new SvgContentNode() { Content = reader.Value });
  283. break;
  284. }
  285. }
  286. catch (Exception exc)
  287. {
  288. Trace.TraceError(exc.Message);
  289. }
  290. }
  291. if (styles.Any())
  292. {
  293. var cssTotal = styles.Select((s) => s.Content).Aggregate((p, c) => p + Environment.NewLine + c);
  294. var cssParser = new Parser();
  295. var sheet = cssParser.Parse(cssTotal);
  296. AggregateSelectorList aggList;
  297. IEnumerable<BaseSelector> selectors;
  298. IEnumerable<SvgElement> elemsToStyle;
  299. foreach (var rule in sheet.StyleRules)
  300. {
  301. aggList = rule.Selector as AggregateSelectorList;
  302. if (aggList != null && aggList.Delimiter == ",")
  303. {
  304. selectors = aggList;
  305. }
  306. else
  307. {
  308. selectors = Enumerable.Repeat(rule.Selector, 1);
  309. }
  310. foreach (var selector in selectors)
  311. {
  312. elemsToStyle = svgDocument.QuerySelectorAll(rule.Selector.ToString(), elementFactory);
  313. foreach (var elem in elemsToStyle)
  314. {
  315. foreach (var decl in rule.Declarations)
  316. {
  317. elem.AddStyle(decl.Name, decl.Term.ToString(), rule.Selector.GetSpecificity());
  318. }
  319. }
  320. }
  321. }
  322. }
  323. if (svgDocument != null) FlushStyles(svgDocument);
  324. return svgDocument;
  325. }
  326. private static void FlushStyles(SvgElement elem)
  327. {
  328. elem.FlushStyles();
  329. foreach (var child in elem.Children)
  330. {
  331. FlushStyles(child);
  332. }
  333. }
  334. /// <summary>
  335. /// Opens an SVG document from the specified <see cref="XmlDocument"/>.
  336. /// </summary>
  337. /// <param name="document">The <see cref="XmlDocument"/> containing the SVG document XML.</param>
  338. /// <exception cref="ArgumentNullException">The <paramref name="document"/> parameter cannot be <c>null</c>.</exception>
  339. public static SvgDocument Open(XmlDocument document)
  340. {
  341. if (document == null)
  342. {
  343. throw new ArgumentNullException("document");
  344. }
  345. var reader = new SvgNodeReader(document.DocumentElement, null);
  346. return Open<SvgDocument>(reader);
  347. }
  348. public static Bitmap OpenAsBitmap(string path)
  349. {
  350. return null;
  351. }
  352. public static Bitmap OpenAsBitmap(XmlDocument document)
  353. {
  354. return null;
  355. }
  356. /// <summary>
  357. /// Renders the <see cref="SvgDocument"/> to the specified <see cref="ISvgRenderer"/>.
  358. /// </summary>
  359. /// <param name="renderer">The <see cref="ISvgRenderer"/> to render the document with.</param>
  360. /// <exception cref="ArgumentNullException">The <paramref name="renderer"/> parameter cannot be <c>null</c>.</exception>
  361. public void Draw(ISvgRenderer renderer)
  362. {
  363. if (renderer == null)
  364. {
  365. throw new ArgumentNullException("renderer");
  366. }
  367. renderer.SetBoundable(this);
  368. this.Render(renderer);
  369. }
  370. /// <summary>
  371. /// Renders the <see cref="SvgDocument"/> to the specified <see cref="Graphics"/>.
  372. /// </summary>
  373. /// <param name="graphics">The <see cref="Graphics"/> to be rendered to.</param>
  374. /// <exception cref="ArgumentNullException">The <paramref name="graphics"/> parameter cannot be <c>null</c>.</exception>
  375. public void Draw(Graphics graphics)
  376. {
  377. if (graphics == null)
  378. {
  379. throw new ArgumentNullException("graphics");
  380. }
  381. var renderer = SvgRenderer.FromGraphics(graphics);
  382. renderer.SetBoundable(this);
  383. this.Render(renderer);
  384. }
  385. /// <summary>
  386. /// Renders the <see cref="SvgDocument"/> and returns the image as a <see cref="Bitmap"/>.
  387. /// </summary>
  388. /// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
  389. public virtual Bitmap Draw()
  390. {
  391. //Trace.TraceInformation("Begin Render");
  392. var size = GetDimensions();
  393. Bitmap bitmap = null;
  394. try
  395. {
  396. bitmap = new Bitmap((int)Math.Round(size.Width), (int)Math.Round(size.Height));
  397. }
  398. catch (ArgumentException e)
  399. {
  400. //When processing too many files at one the system can run out of memory
  401. throw new SvgMemoryException("Cannot process SVG file, cannot allocate the required memory", e);
  402. }
  403. // bitmap.SetResolution(300, 300);
  404. try
  405. {
  406. Draw(bitmap);
  407. }
  408. catch
  409. {
  410. bitmap.Dispose();
  411. throw;
  412. }
  413. //Trace.TraceInformation("End Render");
  414. return bitmap;
  415. }
  416. /// <summary>
  417. /// Renders the <see cref="SvgDocument"/> into a given Bitmap <see cref="Bitmap"/>.
  418. /// </summary>
  419. public virtual void Draw(Bitmap bitmap)
  420. {
  421. //Trace.TraceInformation("Begin Render");
  422. try
  423. {
  424. using (var renderer = SvgRenderer.FromImage(bitmap))
  425. {
  426. renderer.SetBoundable(new GenericBoundable(0, 0, bitmap.Width, bitmap.Height));
  427. //EO, 2014-12-05: Requested to ensure proper zooming out (reduce size). Otherwise it clip the image.
  428. this.Overflow = SvgOverflow.Auto;
  429. this.Render(renderer);
  430. }
  431. }
  432. catch
  433. {
  434. throw;
  435. }
  436. //Trace.TraceInformation("End Render");
  437. }
  438. /// <summary>
  439. /// Renders the <see cref="SvgDocument"/> in given size and returns the image as a <see cref="Bitmap"/>.
  440. /// </summary>
  441. /// <returns>A <see cref="Bitmap"/> containing the rendered document.</returns>
  442. public virtual Bitmap Draw(int rasterWidth, int rasterHeight)
  443. {
  444. var size = GetDimensions();
  445. RasterizeDimensions(ref size, rasterWidth, rasterHeight);
  446. if (size.Width == 0 || size.Height == 0)
  447. return null;
  448. var bitmap = new Bitmap((int)Math.Round(size.Width), (int)Math.Round(size.Height));
  449. try
  450. {
  451. Draw(bitmap);
  452. }
  453. catch
  454. {
  455. bitmap.Dispose();
  456. throw;
  457. }
  458. //Trace.TraceInformation("End Render");
  459. return bitmap;
  460. }
  461. /// <summary>
  462. /// If both or one of raster height and width is not given (0), calculate that missing value from original SVG size
  463. /// while keeping original SVG size ratio
  464. /// </summary>
  465. /// <param name="size"></param>
  466. /// <param name="rasterWidth"></param>
  467. /// <param name="rasterHeight"></param>
  468. public virtual void RasterizeDimensions(ref SizeF size, int rasterWidth, int rasterHeight)
  469. {
  470. if (size == null || size.Width == 0)
  471. return;
  472. // Ratio of height/width of the original SVG size, to be used for scaling transformation
  473. float ratio = size.Height / size.Width;
  474. size.Width = rasterWidth > 0 ? (float)rasterWidth : size.Width;
  475. size.Height = rasterHeight > 0 ? (float)rasterHeight : size.Height;
  476. if (rasterHeight == 0 && rasterWidth > 0)
  477. {
  478. size.Height = (int)(rasterWidth * ratio);
  479. }
  480. else if (rasterHeight > 0 && rasterWidth == 0)
  481. {
  482. size.Width = (int)(rasterHeight / ratio);
  483. }
  484. }
  485. public override void Write(XmlTextWriter writer)
  486. {
  487. //Save previous culture and switch to invariant for writing
  488. var previousCulture = Thread.CurrentThread.CurrentCulture;
  489. try
  490. {
  491. Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
  492. base.Write(writer);
  493. }
  494. finally
  495. {
  496. // Make sure to set back the old culture even an error occurred.
  497. //Switch culture back
  498. Thread.CurrentThread.CurrentCulture = previousCulture;
  499. }
  500. }
  501. public void Write(Stream stream, bool useBom = true)
  502. {
  503. var xmlWriter = new XmlTextWriter(stream, useBom ? Encoding.UTF8 : new System.Text.UTF8Encoding(false));
  504. xmlWriter.Formatting = Formatting.Indented;
  505. xmlWriter.WriteStartDocument();
  506. xmlWriter.WriteDocType("svg", "-//W3C//DTD SVG 1.1//EN", "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd", null);
  507. if (!String.IsNullOrEmpty(this.ExternalCSSHref))
  508. xmlWriter.WriteProcessingInstruction("xml-stylesheet", String.Format("type=\"text/css\" href=\"{0}\"", this.ExternalCSSHref));
  509. this.Write(xmlWriter);
  510. xmlWriter.Flush();
  511. }
  512. public void Write(string path, bool useBom = true)
  513. {
  514. using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
  515. {
  516. this.Write(fs, useBom);
  517. }
  518. }
  519. }
  520. }
  521. #pragma warning restore