Beispiel #1
17
		public override void InitialiseFromXML(XmlTextReader reader, SvgDocument document)
		{
			base.InitialiseFromXML(reader, document);

			//read in the metadata just as a string ready to be written straight back out again
			Content = reader.ReadInnerXml();
		}
Beispiel #2
2
        private static void SetAttributes(SvgElement element, XmlTextReader reader, SvgDocument document)
        {
            //Trace.TraceInformation("Begin SetAttributes");

            string[] styles = null;
            string[] style = null;
            int i = 0;

            while (reader.MoveToNextAttribute())
            {
                // Special treatment for "style"
                if (reader.LocalName.Equals("style"))
                {
                    styles = reader.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    for (i = 0; i < styles.Length; i++)
                    {
                        if (!styles[i].Contains(":"))
                        {
                            continue;
                        }

                        style = styles[i].Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        SetPropertyValue(element, style[0].Trim(), style[1].Trim(), document);
                    }

                    continue;
                }

                SetPropertyValue(element, reader.LocalName, reader.Value, document);
            }

            //Trace.TraceInformation("End SetAttributes");
        }
 private static string RenderSvg(SvgDocument image)
 {
     using (var stream = new MemoryStream())
     {
         image.Write(stream);
         stream.Position = 0;
         using (var reader = new StreamReader(stream))
         {
             var contents = reader.ReadToEnd();
             return contents;
         }
     }
 }
Beispiel #4
1
        private static void SetPropertyValue(SvgElement element, string attributeName, string attributeValue, SvgDocument document)
        {
            var elementType = element.GetType();

            PropertyDescriptorCollection properties;
            if (_propertyDescriptors.Keys.Contains(elementType))
            {
                if (_propertyDescriptors[elementType].Keys.Contains(attributeName))
                {
                    properties = _propertyDescriptors[elementType][attributeName];
                }
                else
                {
                    properties = TypeDescriptor.GetProperties(elementType, new[] { new SvgAttributeAttribute(attributeName) });
                    _propertyDescriptors[elementType].Add(attributeName, properties);
                }
            }
            else
            {
                properties = TypeDescriptor.GetProperties(element.GetType(), new[] { new SvgAttributeAttribute(attributeName) });
                _propertyDescriptors.Add(elementType, new Dictionary<string, PropertyDescriptorCollection>());

                _propertyDescriptors[elementType].Add(attributeName, properties);
            }

            if (properties.Count > 0)
            {
                PropertyDescriptor descriptor = properties[0];

                try
                {
                    descriptor.SetValue(element, descriptor.Converter.ConvertFrom(document, CultureInfo.InvariantCulture, attributeValue));
                }
                catch
                {
                    Trace.TraceWarning(string.Format("Attribute '{0}' cannot be set - type '{1}' cannot convert from string '{2}'.", attributeName, descriptor.PropertyType.FullName, attributeValue));
                }
            }
        }
        protected override Image DrawSvg(SvgDocument svgDoc)
        {
            // GDI+
            Metafile metafile;
            using (var stream = new MemoryStream())
            using (var img = new Bitmap((int)svgDoc.Width.Value, (int)svgDoc.Height.Value)) // Not necessary if you use Control.CreateGraphics().
            using (Graphics ctrlGraphics = Graphics.FromImage(img)) // Control.CreateGraphics()
            {
                IntPtr handle = ctrlGraphics.GetHdc();

                var rect = new RectangleF(0, 0, svgDoc.Width, svgDoc.Height);
                metafile = new Metafile(stream,
                    handle,
                    rect,
                    MetafileFrameUnit.Pixel,
                    EmfType.EmfPlusOnly);

                using (Graphics ig = Graphics.FromImage(metafile))
                {
                    svgDoc.Draw(ig);
                }

                ctrlGraphics.ReleaseHdc(handle);
            }

            return metafile;
        }
Beispiel #6
0
        /// <summary>
        /// Checks the document if it contains the correct information when exported to XML.
        /// </summary>
        /// <param name="svgDocument">The SVG document to check.</param>
        private static void CheckDocument(SvgDocument svgDocument)
        {
            Assert.AreEqual(2, svgDocument.Children.Count);
            Assert.IsInstanceOfType(svgDocument.Children[0], typeof(SvgDefinitionList));
            Assert.IsInstanceOfType(svgDocument.Children[1], typeof(SvgText));

            var textElement = (SvgText)svgDocument.Children[1];
            Assert.AreEqual("IP", textElement.Content);

            var memoryStream = new MemoryStream();
            svgDocument.Write(memoryStream);

            memoryStream.Seek(0, SeekOrigin.Begin);

            var xmlDocument = new XmlDocument();
            xmlDocument.Load(memoryStream);

            Assert.AreEqual(2, xmlDocument.ChildNodes.Count);
            var svgNode = xmlDocument.ChildNodes[1];

            // Filter all significant whitespaces.
            var svgChildren = svgNode.ChildNodes
                .OfType<XmlNode>()
                .Where(item => item.GetType() != typeof(XmlSignificantWhitespace))
                .OfType<XmlNode>()
                .ToArray();

            Assert.AreEqual(2, svgChildren.Length);
            var textNode = svgChildren[1];

            Assert.AreEqual("text", textNode.Name);
            Assert.AreEqual("IP", textNode.InnerText);
        }
Beispiel #7
0
        public Form1()
        {
            InitializeComponent();


            FSvgDoc = new SvgDocument
            {
                Width = 500,
                Height = 500
            };

            FSvgDoc.ViewBox = new SvgViewBox(-250, -250, 500, 500);

            var group = new SvgGroup();
            FSvgDoc.Children.Add(group);

            group.Children.Add(new SvgCircle
            {
                Radius = 100,
                Fill = new SvgColourServer(Color.Red),
                Stroke = new SvgColourServer(Color.Black),
                StrokeWidth = 2
            });

            var stream = new MemoryStream();
            FSvgDoc.Write(stream);
            textBox1.Text = Encoding.UTF8.GetString(stream.GetBuffer());

            pictureBox1.Image = FSvgDoc.Draw();
        }
Beispiel #8
0
		public void LoadText(string text)
		{
			if (text == null) throw new ArgumentNullException(nameof(text));

			var svg = SvgDocument.Parse(text);
			this.Content = svg;
		}
Beispiel #9
0
 public void EnsureSvg()
 {
     if (svg == null)
     {
         svg = new SvgDocument();
         RenderSvg();
     }
 }
 public SvgImage(SvgDocument svg)
 {
     this.svg = svg;
     this.frames = new List<IFrame>(1)
     {
         new SvgFrame(svg)
     };
 }
Beispiel #11
0
 private static Bitmap DrawBitmap(SvgDocument doc, int width, int height)
 {
     doc.Width = width;
     doc.Height = height;
     var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
     doc.Draw(bmp);
     return bmp;
 }
Beispiel #12
0
 public SvgIdManager(SvgDocument doc, ISvgEventCaller caller, RemoteContext remoteContext)
     : base(doc)
 {
     FCaller = caller;
     RemoteContext = remoteContext;
     doc.ChildAdded += element_ChildAdded;
     doc.AttributeChanged += element_AttributeChanged;
     doc.ContentChanged += element_ContentChanged;
 }
Beispiel #13
0
 /// <summary>
 /// Makes sure that the image does not exceed the maximum size, while preserving aspect ratio.
 /// </summary>
 /// <param name="document">The SVG document to resize.</param>
 /// <returns>Returns a resized or the original document depending on the document.</returns>
 private static SvgDocument AdjustSize(SvgDocument document)
 {
     if (document.Height > MaximumSize.Height)
     {
         document.Width = (int)((document.Width / (double)document.Height) * MaximumSize.Height);
         document.Height = MaximumSize.Height;
     }
     return document;
 }
Beispiel #14
0
 private void RenderSvg(SvgDocument svgDoc)
 {
     //var render = new DebugRenderer();
     //svgDoc.Draw(render);
     svgImage.Image = svgDoc.Draw();
     
     string outputDir;
     if (svgDoc.BaseUri == null)
         outputDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath); 
     else
         outputDir = System.IO.Path.GetDirectoryName(svgDoc.BaseUri.LocalPath);
     svgImage.Image.Save(System.IO.Path.Combine(outputDir, "output.png"));
 }
Beispiel #15
0
        /// <summary>
        /// Creates an <see cref="SvgElement"/> from the current node in the specified <see cref="XmlTextReader"/>.
        /// </summary>
        /// <param name="reader">The <see cref="XmlTextReader"/> containing the node to parse into a subclass of <see cref="SvgElement"/>.</param>
        /// <param name="document">The <see cref="SvgDocument"/> that the created element belongs to.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="reader"/> and <paramref name="document"/> parameters cannot be <c>null</c>.</exception>
        public static SvgElement CreateElement(XmlTextReader reader, SvgDocument document)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (document == null)
            {
                throw new ArgumentNullException("document");
            }

            return CreateElement(reader, false, document);
        }
Beispiel #16
0
        public void TextPropertyAffectsSvgOutput()
        {
            var document = new SvgDocument();
            document.Children.Add(new SvgText { Text = "test1" });
            using(var stream = new MemoryStream())
            {
                document.Write(stream);
                stream.Position = 0;

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(stream);
                Assert.AreEqual("test1", xmlDoc.DocumentElement.FirstChild.InnerText);
            }
        }
Beispiel #17
0
		private void OnContentChanged(SvgDocument svg)
		{
			if (this._renderer != null)
			{
				this._renderer.Dispose();
				this._renderer = null;
			}

			if (svg != null && this._canvasControl != null)
			{
				this._renderer = new Win2dRenderer(this._canvasControl, svg);
				this._canvasControl?.Invalidate();
			}
		}
Beispiel #18
0
		public async Task LoadFileAsync(StorageFile file)
		{
			if (file == null) throw new ArgumentNullException(nameof(file));

			using (var stream = await WindowsRuntimeStorageExtensions.OpenStreamForReadAsync(file))
			using (var reader = new StreamReader(stream))
			{
				var xml = new XmlDocument();
				xml.LoadXml(reader.ReadToEnd(), new XmlLoadSettings { ProhibitDtd = false });
				var svgDocument = SvgDocument.Parse(xml);

				this.Content = svgDocument;
			}
		}
 public static SvgPaintServer Create(string value, SvgDocument document)
 {
     // If it's pointing to a paint server
     if (string.IsNullOrEmpty(value) || value.ToLower().Trim() == "none")
     {
         return new SvgColourServer(Color.Transparent);
     }
     else if (value.IndexOf("url(#") > -1)
     {
         Match match = _urlRefPattern.Match(value);
         Uri id = new Uri(match.Groups[1].Value, UriKind.Relative);
         return (SvgPaintServer)document.IdManager.GetElementById(id);
     }
     else // Otherwise try and parse as colour
     {
         return new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Trim()));
     }
 }
Beispiel #20
0
 public static SvgPaintServer Create(string value, SvgDocument document)
 {
     // If it's pointing to a paint server
     if (string.IsNullOrEmpty(value))
     {
         return SvgColourServer.NotSet;
     }
     else if (value == "inherit")
     {
         return SvgColourServer.Inherit;
     }
     else if (value == "currentColor")
     {
         return new SvgDeferredPaintServer(document, value);
     }
     else if (value.IndexOf("url(#") > -1)
     {
         Match match = _urlRefPattern.Match(value);
         Uri id = new Uri(match.Groups[1].Value, UriKind.Relative);
         return (SvgPaintServer)document.IdManager.GetElementById(id);
     }
     // If referenced to to a different (linear or radial) gradient
     else if (document.IdManager.GetElementById(value) != null && document.IdManager.GetElementById(value).GetType().BaseType == typeof(SvgGradientServer))
     {
         return (SvgPaintServer)document.IdManager.GetElementById(value);
     }
     else if (value.StartsWith("#")) // Otherwise try and parse as colour
     {
         try
         {
             return new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Trim()));
         }
         catch
         {
             return new SvgDeferredPaintServer(document, value);
         }
     }
     else
     {
         return new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Trim()));
     }
 }
Beispiel #21
0
 public SvgRenderer()
 {
     _svg = new SvgDocument();
 }
        /// <summary>
        /// 把图表转成图片
        /// </summary>
        /// <param name="context"></param>

        public void SaveImage(HttpContext context)
        {
            if (context.Request.Form["svg"] != null)
            {
                string tType     = "image/png";
                string tSvg      = context.Request.Form["svg"].ToString();
                string tFileName = "";

                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                tFileName = rand.Next().ToString();

                MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));

                MemoryStream tStream = new MemoryStream();
                string       tTmp    = new Random().Next().ToString();

                string tExt        = "";
                string tTypeString = "";

                switch (tType)
                {
                case "image/png":
                    tTypeString = "-m image/png";
                    tExt        = "png";
                    break;

                case "image/jpeg":
                    tTypeString = "-m image/jpeg";
                    tExt        = "jpg";
                    break;

                case "application/pdf":
                    tTypeString = "-m application/pdf";
                    tExt        = "pdf";
                    break;

                case "image/svg+xml":
                    tTypeString = "-m image/svg+xml";
                    tExt        = "svg";
                    break;
                }

                if (tTypeString != "")
                {
                    //string tWidth = context.Request.Form["width"].ToString();
                    //string tWidth = "0";
                    Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
                    switch (tExt)
                    {
                    case "jpg":
                        tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);
                        break;

                    case "png":

                        tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                        break;

                    case "pdf":
                        PdfWriter tWriter = null;
                        iTextSharp.text.Document tDocumentPdf = null;
                        try
                        {
                            tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                            tDocumentPdf = new iTextSharp.text.Document(new iTextSharp.text.Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                            tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                            iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray());
                            tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                            tStream = new MemoryStream();
                            tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream);
                            tDocumentPdf.Open();
                            tDocumentPdf.NewPage();
                            tDocumentPdf.Add(tGraph);
                            tDocumentPdf.CloseDocument();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                        finally
                        {
                            tDocumentPdf.Close();
                            tDocumentPdf.Dispose();
                            tWriter.Close();
                            tWriter.Dispose();
                            tData.Dispose();
                            tData.Close();
                        }
                        break;

                    case "svg":
                        tStream = tData;
                        break;
                    }
                    System.IO.MemoryStream ms    = new System.IO.MemoryStream(tStream.ToArray());
                    System.Drawing.Image   image = System.Drawing.Image.FromStream(ms);
                    string savePath = context.Server.MapPath("image/");

                    if (!Directory.Exists(savePath))
                    {
                        Directory.CreateDirectory(savePath);
                    }
                    savePath += tFileName + "." + tExt;
                    string SavePathImage = tFileName + "." + tExt;
                    context.Session["FirstImage"] = savePath;
                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Png);
                    image.Dispose();
                    context.Response.Write(tFileName + "." + tExt);
                }
            }
        }
Beispiel #23
0
        /// <summary>
        /// Add event listeners for on* events within the document
        /// </summary>
        private void InitializeEvents()
        {
            SvgDocument document = (SvgDocument)window.Document;

            document.NamespaceManager.AddNamespace("svg", "http://www.w3.org/2000/svg");

            XmlNodeList nodes = document.SelectNodes(@"//*[namespace-uri()='http://www.w3.org/2000/svg']
                                                   [local-name()='svg' or
                                                    local-name()='g' or
                                                    local-name()='defs' or
                                                    local-name()='symbol' or
                                                    local-name()='use' or
                                                    local-name()='switch' or
                                                    local-name()='image' or
                                                    local-name()='path' or
                                                    local-name()='rect' or
                                                    local-name()='circle' or
                                                    local-name()='ellipse' or
                                                    local-name()='line' or
                                                    local-name()='polyline' or
                                                    local-name()='polygon' or
                                                    local-name()='text' or
                                                    local-name()='tref' or
                                                    local-name()='tspan' or
                                                    local-name()='textPath' or
                                                    local-name()='altGlyph' or
                                                    local-name()='a' or
                                                    local-name()='foreignObject']
                                                /@*[name()='onfocusin' or
                                                    name()='onfocusout' or
                                                    name()='onactivate' or
                                                    name()='onclick' or
                                                    name()='onmousedown' or
                                                    name()='onmouseup' or
                                                    name()='onmouseover' or
                                                    name()='onmousemove' or
                                                    name()='onmouseout' or
                                                    name()='onload']", document.NamespaceManager);

            foreach (XmlNode node in nodes)
            {
                IAttribute att         = (IAttribute)node;
                IEventTarget targ      = (IEventTarget)att.OwnerElement;
                ScriptEventMonitor mon = new ScriptEventMonitor((VsaScriptEngine)GetScriptEngineByMimeType(""), att, window);
                string eventName       = null;
                switch (att.Name)
                {
                case "onfocusin":
                    eventName = "focusin";
                    break;

                case "onfocusout":
                    eventName = "focusout";
                    break;

                case "onactivate":
                    eventName = "activate";
                    break;

                case "onclick":
                    eventName = "click";
                    break;

                case "onmousedown":
                    eventName = "mousedown";
                    break;

                case "onmouseup":
                    eventName = "mouseup";
                    break;

                case "onmouseover":
                    eventName = "mouseover";
                    break;

                case "onmousemove":
                    eventName = "mousemove";
                    break;

                case "onmouseout":
                    eventName = "mouseout";
                    break;

                case "onload":
                    eventName = "SVGLoad";
                    break;
                }
                targ.AddEventListener(eventName, new EventListener(mon.EventHandler), false);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Collect the text in all script elements, build engine and execute.
        /// </summary>
        private void ExecuteScripts()
        {
            Hashtable codeByMimeType = new Hashtable();
            StringBuilder codeBuilder;
            SvgDocument document = (SvgDocument)window.Document;

            XmlNodeList scripts = document.GetElementsByTagName("script", SvgDocument.SvgNamespace);
            StringBuilder code  = new StringBuilder();

            foreach (XmlElement script in scripts)
            {
                string type = script.GetAttribute("type");

                if (GetScriptEngineByMimeType(type) != null)
                {
                    // make sure we have a StringBuilder for this MIME type
                    if (!codeByMimeType.Contains(type))
                    {
                        codeByMimeType[type] = new StringBuilder();
                    }

                    // grab this MIME type's codeBuilder
                    codeBuilder = (StringBuilder)codeByMimeType[type];

                    if (script.HasChildNodes)
                    {
                        // process each child that is text node or a CDATA section
                        foreach (XmlNode node in script.ChildNodes)
                        {
                            if (node.NodeType == XmlNodeType.CDATA || node.NodeType == XmlNodeType.Text)
                            {
                                codeBuilder.Append(node.Value);
                            }
                        }
                    }

                    if (script.HasAttribute("href", "http://www.w3.org/1999/xlink"))
                    {
                        string href = script.GetAttribute("href", "http://www.w3.org/1999/xlink");
                        Uri baseUri = new Uri(((XmlDocument)((ISvgWindow)window).Document).BaseURI);
                        Uri hUri    = new Uri(baseUri, href);
                        ExtendedHttpWebRequestCreator creator = new ExtendedHttpWebRequestCreator();
                        ExtendedHttpWebRequest request        = (ExtendedHttpWebRequest)creator.Create(hUri);
                        ExtendedHttpWebResponse response      = (ExtendedHttpWebResponse)request.GetResponse();
                        Stream rs       = response.GetResponseStream();
                        StreamReader sr = new StreamReader(rs);
                        codeBuilder.Append(sr.ReadToEnd());
                        rs.Close();
                    }
                }
            }

            // execute code for all script engines
            foreach (string mimeType in codeByMimeType.Keys)
            {
                codeBuilder = (StringBuilder)codeByMimeType[mimeType];

                if (codeBuilder.Length > 0)
                {
                    ScriptEngine engine = GetScriptEngineByMimeType(mimeType);
                    engine.Execute(codeBuilder.ToString());
                }
            }

            // load the root element
            ((ISvgWindow)window).Document.RootElement.DispatchEvent(new Event("SVGLoad", false, true));
        }
Beispiel #25
0
        public static SvgDocument Generate(ISvgRenderableColumn[] columns, ILegendGroup[] legend)
        {
            //generating headers
            SvgGroup       headerGroup      = new SvgGroup();
            SvgPaintServer blackPaint       = new SvgColourServer(System.Drawing.Color.Black);
            double         horizontalOffset = 0.0;
            double         headerHeight     = 0;

            for (int i = 0; i < columns.Length; i++)
            {
                RenderedSvg  heading = columns[i].RenderHeader();
                SvgRectangle rect    = new SvgRectangle();
                headerHeight = heading.RenderedSize.Height;
                rect.Width   = Helpers.dtos(heading.RenderedSize.Width);
                rect.Height  = Helpers.dtos(heading.RenderedSize.Height);
                rect.X       = Helpers.dtos(horizontalOffset);
                rect.Y       = Helpers.dtos(0.0);
                rect.Stroke  = blackPaint;

                heading.SVG.Transforms.Add(new SvgTranslate((float)(horizontalOffset + heading.RenderedSize.Width * 0.5), (float)heading.RenderedSize.Height * 0.9f));
                heading.SVG.Transforms.Add(new SvgRotate((float)-90.0));

                headerGroup.Children.Add(rect);
                headerGroup.Children.Add(heading.SVG);
                horizontalOffset += heading.RenderedSize.Width;
            }
            //generating columns
            SvgGroup columnsGroup = new SvgGroup();
            double   columnHeight = 0.0;

            horizontalOffset = 0.0;
            columnsGroup.Transforms.Add(new SvgTranslate(0.0f, (float)headerHeight));
            for (int i = 0; i < columns.Length; i++)
            {
                RenderedSvg  column = columns[i].RenderColumn();
                SvgRectangle rect   = new SvgRectangle();
                columnHeight = column.RenderedSize.Height;
                rect.Width   = Helpers.dtos(column.RenderedSize.Width);
                rect.Height  = Helpers.dtos(column.RenderedSize.Height);
                rect.X       = Helpers.dtos(horizontalOffset);
                rect.Y       = Helpers.dtos(0.0);
                rect.Stroke  = blackPaint;

                column.SVG.Transforms.Add(new SvgTranslate((float)(horizontalOffset)));

                columnsGroup.Children.Add(rect);
                columnsGroup.Children.Add(column.SVG);

                horizontalOffset += column.RenderedSize.Width;
            }

            //generating legend group
            SvgGroup legendGroup = new SvgGroup();

            const float legendYGap    = 30.0f;
            const float legendXOffset = 10.0f;


            legendGroup.Transforms.Add(new SvgTranslate(legendXOffset, Helpers.dtos(headerHeight + columnHeight + legendYGap)));

            const float titleYoffset    = 60.0f;
            const float itemsYoffset    = 20.0f;
            const float itemYgap        = 20.0f;
            const float interGroupYgap  = 15.0f;
            const float itemImageWidth  = 64.0f;
            const float itemImageHeight = 32.0f;
            const float descrXoffset    = 150.0f;

            SvgText legendTitle = new SvgText("Условные обозначения");

            legendTitle.FontSize = 22;
            legendTitle.Fill     = new SvgColourServer(System.Drawing.Color.Black);
            legendTitle.Transforms.Add(new SvgTranslate(30.0f, Helpers.dtos(titleYoffset * 0.25f)));
            legendGroup.Children.Add(legendTitle);

            float currGroupOffset = 0.0f;
            int   k = 0;

            foreach (ILegendGroup group in legend)
            {
                //title
                SvgText groupTitle = new SvgText(group.GroupName);
                groupTitle.FontSize = new SvgUnit((float)18);
                groupTitle.Fill     = new SvgColourServer(System.Drawing.Color.Black);
                groupTitle.Transforms.Add(new SvgTranslate(0.0f, currGroupOffset + titleYoffset));
                legendGroup.Children.Add(groupTitle);

                //items
                var items = group.Items;

                int j = 0;

                SvgElement[] fragments = items.Select(item => item.GetPresentation(itemImageWidth, itemImageHeight)).ToArray();

                foreach (var item in items)
                {
                    if (fragments[j] == null)
                    {
                        continue;
                    }

                    float yOffset = currGroupOffset + titleYoffset + itemsYoffset + j * (itemYgap + itemImageHeight);

                    if (fragments[j] is SvgFragment)
                    {
                        SvgFragment fragment = (SvgFragment)fragments[j];
                        fragment.X = 0;
                        fragment.Y = yOffset;
                    }
                    else
                    {
                        fragments[j].Transforms.Add(new SvgTranslate(0, yOffset));
                    }

                    legendGroup.Children.Add(fragments[j]);

                    SvgText text = new SvgText(item.Description);
                    text.FontSize = new SvgUnit((float)14);
                    text.Fill     = new SvgColourServer(System.Drawing.Color.Black);
                    text.Transforms.Add(new SvgTranslate(descrXoffset, yOffset + itemImageHeight * 0.5f));
                    legendGroup.Children.Add(text);
                    j++;
                }
                currGroupOffset += titleYoffset + itemsYoffset + (itemYgap + itemImageHeight) * items.Length + interGroupYgap;
                k++;
            }


            //gathering definitions
            SvgDefinitionList allDefs = new SvgDefinitionList();

            for (int i = 0; i < columns.Length; i++)
            {
                SvgDefinitionList defs = columns[i].Definitions;
                foreach (SvgPatternServer def in defs.Children)
                {
                    //overridings tile size
                    allDefs.Children.Add(def);
                }
            }

            SvgDocument result = new SvgDocument();

            result.Children.Add(allDefs);
            result.Width  = Helpers.dtos(horizontalOffset);
            result.Height = Helpers.dtos((headerHeight + columnHeight + legendYGap + currGroupOffset));
            result.Fill   = new SvgColourServer(System.Drawing.Color.White);
            result.Children.Add(headerGroup);
            result.Children.Add(columnsGroup);
            result.Children.Add(legendGroup);

            return(result);
        }
Beispiel #26
0
        public static Image FromSource(string source, int?width, int?height)
        {
            try
            {
                Uri    uri       = new Uri(source);
                string localPath = "";

                switch (uri.HostNameType)
                {
                case UriHostNameType.Basic:
                    localPath = uri.LocalPath;
                    break;

                default:
                    WebClient web = new WebClient();
                    localPath = Path.GetTempFileName();
                    web.DownloadFile(uri, localPath);
                    break;
                }

                if (File.Exists(localPath))
                {
                    Bitmap image;

                    switch (Path.GetExtension(localPath).ToLower())
                    {
                    case ".svg":
                        SvgDocument svg = SvgDocument.Open(localPath);
                        image = svg.Draw(width ?? (int)svg.Width.Value, height ?? (int)svg.Height.Value);

                        //using (TextReader tr = new StreamReader(localPath))
                        //{
                        //    var t = new NGraphics.SvgReader(tr);
                        //    var i = NGraphics.Platforms.Current.CreateImageCanvas(t.Graphic.Size);
                        //    t.Graphic.Draw(i);

                        //    using (MemoryStream ms = new MemoryStream())
                        //    {
                        //        i.GetImage().SaveAsPng(ms);
                        //        image = new Bitmap(Bitmap.FromStream(ms));
                        //    }
                        //}
                        break;

                    default:
                        image = System.Drawing.Image.FromFile(localPath) as Bitmap;
                        break;
                    }

                    if (image != null)
                    {
                        Image result = new Image(width ?? image.Width, height ?? image.Height);

                        using (Graphics g = Graphics.FromImage(result.Bitmap))
                        //if (result.Width != image.Width || result.Height != image.Height)
                        {
                            g.DrawImage(image, 0, 0, result.Width, result.Height);
                        }
                        //else
                        //{
                        //    g.DrawImageUnscaled(image, 0, 0);
                        //}

                        image.Dispose();

                        return(result);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(null);
        }
 public SvgFontFaceSrcElement(string prefix, string localname, string ns, SvgDocument doc)
     : base(prefix, localname, ns, doc)
 {
 }
Beispiel #28
0
 /// <summary>
 /// Open SVG document from XML document.
 /// </summary>
 /// <param name="xml">XML document.</param>
 /// <returns>Open SVG document.</returns>
 protected virtual SvgDocument OpenSvg(XmlDocument xml)
 {
     return(SvgDocument.Open(xml));
 }
Beispiel #29
0
        private bool PassesSwitchAllTest(ISvgTests element)
        {
            SvgDocument ownerDocument = ((SvgElement)element).OwnerDocument;

            bool requiredFeatures = true;

            if (element.RequiredFeatures.NumberOfItems > 0)
            {
                foreach (string req in element.RequiredFeatures)
                {
                    if (!ownerDocument.Supports(req, string.Empty))
                    {
                        requiredFeatures = false;
                        break;
                    }
                }
            }
            if (!requiredFeatures)
            {
                return(false);
            }

            bool requiredExtensions = true;

            if (element.RequiredExtensions.NumberOfItems > 0)
            {
                foreach (string req in element.RequiredExtensions)
                {
                    if (!ownerDocument.Supports(req, string.Empty))
                    {
                        requiredExtensions = false;
                        break;
                    }
                }
            }
            if (!requiredExtensions)
            {
                return(false);
            }

            bool systemLanguage = true;

            if (element.SystemLanguage.NumberOfItems > 0)
            {
                systemLanguage = false;
                // TODO: or if one of the languages indicated by user preferences exactly
                // equals a prefix of one of the languages given in the value of this
                // parameter such that the first tag character following the prefix is "-".

                foreach (string req in element.SystemLanguage)
                {
                    if (string.Equals(req, _currentLang, StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(req, _currentLangName, StringComparison.OrdinalIgnoreCase))
                    {
                        systemLanguage = true;
                    }
                }
            }

            return(systemLanguage);
        }
Beispiel #30
0
 /// <summary>
 /// Draw SVG.
 /// </summary>
 /// <param name="svgDoc">SVG document to draw.</param>
 /// <returns>SVG as image.</returns>
 protected virtual Image DrawSvg(SvgDocument svgDoc)
 {
     return(svgDoc.Draw());
 }
Beispiel #31
0
        public SvgDocument SvgFromFile(string path)
        {
            var svgDocument = SvgDocument.Open(path);

            return(svgDocument);
        }
Beispiel #32
0
        private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            //render svg
            var lstFiles = sender as ListBox;
            var fileName = lstFiles.SelectedItem.ToString();

            if (fileName.StartsWith("#"))
            {
                return;
            }

            //display png
            var png = Image.FromFile(_pngBasePath + Path.GetFileNameWithoutExtension(fileName) + ".png");

            picPng.Image = png;

            var doc = new SvgDocument();

            try
            {
                Debug.Print(fileName);
                doc = SvgDocument.Open(_svgBasePath + fileName);
                if (fileName.StartsWith("__"))
                {
                    picSvg.Image = doc.Draw();
                }
                else
                {
                    var img = new Bitmap(480, 360);
                    doc.Draw(img);
                    picSvg.Image = img;
                }

                this.boxConsoleLog.AppendText("\n\nWC3 TEST " + fileName + "\n");
                this.boxDescription.Text = GetDescription(doc);
            }
            catch (Exception ex)
            {
                this.boxConsoleLog.AppendText("Result: TEST FAILED\n");
                this.boxConsoleLog.AppendText("SVG RENDERING ERROR for " + fileName + "\n");
                this.boxConsoleLog.AppendText(ex.ToString());
                picSvg.Image = null;
            }

            //save load
            try
            {
                using (var memStream = new MemoryStream())
                {
                    doc.Write(memStream);
                    memStream.Position = 0;
                    var reader       = new StreamReader(memStream);
                    var tempFilePath = Path.Combine(Path.GetTempPath(), "test.svg");
                    System.IO.File.WriteAllText(tempFilePath, reader.ReadToEnd());
                    memStream.Position = 0;
                    var baseUri = doc.BaseUri;
                    doc         = SvgDocument.Open(tempFilePath);
                    doc.BaseUri = baseUri;

                    if (fileName.StartsWith("__"))
                    {
                        picSaveLoad.Image = doc.Draw();
                    }
                    else
                    {
                        var img = new Bitmap(480, 360);
                        doc.Draw(img);
                        picSaveLoad.Image = img;
                    }
                }
            }
            catch (Exception ex)
            {
                this.boxConsoleLog.AppendText("Result: TEST FAILED\n");
                this.boxConsoleLog.AppendText("SVG SERIALIZATION ERROR for " + fileName + "\n");
                this.boxConsoleLog.AppendText(ex.ToString());
                picSaveLoad.Image = null;
            }

            //compare svg to png
            try
            {
                picSVGPNG.Image = PixelDiff((Bitmap)picPng.Image, (Bitmap)picSvg.Image);
            }
            catch (Exception ex)
            {
                this.boxConsoleLog.AppendText("Result: TEST FAILED\n");
                this.boxConsoleLog.AppendText("SVG TO PNG COMPARISON ERROR for " + fileName + "\n");
                this.boxConsoleLog.AppendText(ex.ToString());
                picSVGPNG.Image = null;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.Form["type"] != null && Request.Form["svg"] != null && Request.Form["filename"] != null)
                {
                    string tType     = Request.Form["type"].ToString();
                    string tSvg      = Request.Form["svg"].ToString();
                    string tFileName = Request.Form["filename"].ToString();
                    if (tFileName == "")
                    {
                        tFileName = "chart";
                    }
                    MemoryStream tData   = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));
                    string       stData  = Convert.ToString(tData);
                    MemoryStream tStream = new MemoryStream();
                    string       tTmp    = new Random().Next().ToString();

                    string tExt        = "";
                    string tTypeString = "";

                    switch (tType)
                    {
                    case "image/png":
                        tTypeString = "-m image/png";
                        tExt        = "png";
                        break;

                    case "image/jpeg":
                        tTypeString = "-m image/jpeg";
                        tExt        = "jpg";
                        break;

                    case "application/pdf":
                        tTypeString = "-m application/pdf";
                        tExt        = "pdf";
                        break;

                    case "image/svg+xml":
                        tTypeString = "-m image/svg+xml";
                        tExt        = "svg";
                        break;
                    }

                    if (tTypeString != "")
                    {
                        string          tWidth  = Request.Form["width"].ToString();
                        Svg.SvgDocument tSvgObj = SvgDocument.Open(stData);
                        switch (tExt)
                        {
                        case "jpg":
                            tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);
                            break;

                        case "png":
                            tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                            break;

                        case "pdf":
                            PdfWriter tWriter      = null;
                            Document  tDocumentPdf = null;
                            try
                            {
                                tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                                tDocumentPdf = new Document(new Rectangle((float)tSvgObj.Width, (float)tSvgObj.Height));
                                tDocumentPdf.SetMargins(0.0f, 0.0f, 0.0f, 0.0f);
                                iTextSharp.text.Image tGraph = iTextSharp.text.Image.GetInstance(tStream.ToArray());
                                tGraph.ScaleToFit((float)tSvgObj.Width, (float)tSvgObj.Height);

                                tStream = new MemoryStream();
                                tWriter = PdfWriter.GetInstance(tDocumentPdf, tStream);
                                tDocumentPdf.Open();
                                tDocumentPdf.NewPage();
                                tDocumentPdf.Add(tGraph);
                                tDocumentPdf.CloseDocument();
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                tDocumentPdf.Close();
                                tDocumentPdf.Dispose();
                                tWriter.Close();
                                tWriter.Dispose();
                                tData.Dispose();
                                tData.Close();
                            }
                            break;

                        case "svg":
                            tStream = tData;
                            break;
                        }

                        Response.ClearContent();
                        Response.ClearHeaders();
                        Response.ContentType = tType;
                        Response.AppendHeader("Content-Disposition", "attachment; filename=" + tFileName + "." + tExt + "");
                        Response.BinaryWrite(tStream.ToArray());
                        Response.End();
                    }
                }
            }
        }
Beispiel #34
0
        public static Image GetBitmap(SvgImageElement element)
        {
            var comparer = StringComparison.OrdinalIgnoreCase;

            if (!element.IsSvgImage)
            {
                if (!element.Href.AnimVal.StartsWith("data:", comparer))
                {
                    SvgUriReference svgUri      = element.UriReference;
                    string          absoluteUri = svgUri.AbsoluteUri;
                    if (string.IsNullOrWhiteSpace(absoluteUri))
                    {
                        return(null); // most likely, the image does not exist...
                    }
                    if (absoluteUri.StartsWith("#", StringComparison.OrdinalIgnoreCase))
                    {
                        Debug.WriteLine("Uri: " + absoluteUri); // image elements can't reference elements in an svg file
                        return(null);
                    }

                    Uri imageUri = new Uri(svgUri.AbsoluteUri);
                    if (imageUri.IsFile && File.Exists(imageUri.LocalPath))
                    {
                        return(Image.FromFile(imageUri.LocalPath, element.ColorProfile != null));
                    }

                    WebResponse resource = svgUri.ReferencedResource;
                    if (resource == null)
                    {
                        return(null);
                    }

                    Stream stream = resource.GetResponseStream();
                    if (stream == null)
                    {
                        return(null);
                    }

                    return(Image.FromStream(stream, element.ColorProfile != null));
                }

                string sURI = element.Href.AnimVal.Replace(" ", string.Empty).Trim();
                sURI = sURI.Replace(@"\n", string.Empty);
                int nColon     = sURI.IndexOf(":", comparer);
                int nSemiColon = sURI.IndexOf(";", comparer);
                int nComma     = sURI.IndexOf(",", comparer);

                string sMimeType = sURI.Substring(nColon + 1, nSemiColon - nColon - 1);
                string sContent  = sURI.Substring(nComma + 1);

                sContent = sContent.Replace('-', '+').Replace('_', '/');
                sContent = sContent.PadRight(4 * ((sContent.Length + 3) / 4), '=');
                byte[] bResult = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                             0, sContent.Length);

                if (sMimeType.Equals("image/svg+xml", StringComparison.OrdinalIgnoreCase))
                {
                    GdiGraphicsRenderer renderer = new GdiGraphicsRenderer(true, false);

                    var currentWindow = element.OwnerDocument.Window as SvgWindow;
                    var svgWindow     = currentWindow.CreateOwnedWindow();
                    renderer.Window = svgWindow;

                    SvgDocument doc      = svgWindow.CreateEmptySvgDocument();
                    bool        isGZiped = sContent.StartsWith(SvgConstants.GZipSignature, StringComparison.Ordinal);
                    if (isGZiped)
                    {
                        byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(),
                                                                        0, sContent.Length);
                        using (var stream = new MemoryStream(imageBytes))
                        {
                            using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress))
                            {
                                doc.Load(zipStream);
                            }
                        }
                    }
                    else
                    {
                        var svgData     = Convert.FromBase64String(Convert.ToBase64String(bResult));
                        var svgFragment = Encoding.ASCII.GetString(svgData);

                        doc.LoadXml(svgFragment);
                    }
                    svgWindow.Document = doc;

                    SvgSvgElement elm = (SvgSvgElement)doc.RootElement;

                    int winWidth  = (int)elm.Width.BaseVal.Value;
                    int winHeight = (int)elm.Height.BaseVal.Value;
                    if (winWidth == 0 || winHeight == 0)
                    {
                        var size = elm.GetSize();
                        winWidth  = (int)size.Width;
                        winHeight = (int)size.Height;
                    }

                    svgWindow.Resize(winWidth, winHeight);

                    renderer.Render(elm as SvgElement);
                    Image img = renderer.RasterImage;

                    return(img);
                }

                MemoryStream ms = new MemoryStream(bResult);
                return(Image.FromStream(ms, element.ColorProfile != null));
            }
            return(null);
        }
        public void OnNewPageRequested(GraphicsContext context, DeviceDescription description)
        {
            _currentImage = new SvgDocument
            {
                Width = new SvgUnit(SvgUnitType.Pixel, _mapper.Height),
                Height = new SvgUnit(SvgUnitType.Pixel, _mapper.Width)
            };

            _images.Add(_currentImage);
        }
Beispiel #36
0
 public NodeRender(SvgDocument document, int nodeId)
 {
     Document = document;
     NodeId   = nodeId;
 }
Beispiel #37
0
        void loadMap(string mapPath)
        {
            currentMapPath = mapPath;

            // Variables
            Jumps.Value      = 0;
            CoinsCount.Value = 0;

            // Reset game objects
            GameObjects.RemoveAll(o => o is Coin || o is Platform || o is Door);

            // Create map tiles
            var doc      = SvgDocument.Open(mapPath);
            var elements = doc.Children.FindSvgElementsOf <SvgPath>();

            // get images

            var patterns = doc.Children.FindSvgElementsOf <SvgPatternServer>();
            var images   = new Dictionary <string, Texture2D>();

            foreach (var pattern in patterns)
            {
                var image = pattern.Children.FindSvgElementsOf <SvgImage>().FirstOrDefault();
                if (image == null)
                {
                    continue;
                }

                if (!string.IsNullOrWhiteSpace(image.Href))
                {
                    var v          = image.Href.ToString() ?? string.Empty;
                    var startIndex = v.IndexOf(',') + 1;
                    var len        = v.Length - startIndex;

                    var base64  = v.Substring(startIndex, len).TrimStart();
                    var texture = convertBase64ToTexure(base64);

                    images.Add(pattern.ID, texture);
                }
            }

            // Load new platforms
            var platformsToLoad = new List <Platform>();

            var maxMapX = 0;
            var maxMapY = 0;

            playerStart = new Vector2(0, 0);
            playerExit  = new Vector2(0, 0);

            foreach (var elem in elements)
            {
                // colors
                var fillColor   = elem.Fill?.ToString() ?? "#FF0000";
                var strokeColor = elem.Stroke?.ToString();

                fillColor = fillColor.TrimStart("url(".ToArray()).TrimEnd(")".ToArray());

                if (fillColor == null || !fillColor.StartsWith("#"))
                {
                    fillColor = "#FF0000";
                }

                if (strokeColor == null || !strokeColor.StartsWith("#"))
                {
                    strokeColor = null;
                }

                var       imageKey  = fillColor.TrimStart('#');
                Texture2D imageData = null;

                if (images.ContainsKey(imageKey))
                {
                    imageData = images[imageKey];
                    fillColor = "#FF0000";
                }

                // dimensions
                var x = (int)Math.Round(elem.Bounds.X, 1);
                var y = (int)Math.Round(elem.Bounds.Y, 1);
                var w = (int)Math.Round(elem.Bounds.Width, 1);
                var h = (int)Math.Round(elem.Bounds.Height, 1);

                // create poly
                var vertexes = elem.PathData.Select(d => new Vector2(d.Start.X, d.Start.Y))
                               .Union(elem.PathData.Select(d => new Vector2(d.End.X, d.End.Y)))
                               .Distinct().ToArray();

                Debug.WriteLine($"[shape]");
                Debug.WriteLine($"size: {x} {y} - {w} x {h}");
                Debug.WriteLine($"verts: {vertexes.Length}");

                if (fillColor == "#000001")
                {
                    playerStart.X = x;
                    playerStart.Y = y;
                }
                else if (fillColor == "#000002")
                {
                    // Door
                    playerExit.X = x;
                    playerExit.Y = y;
                }
                else
                {
                    // Platform
                    var platform = new Platform(fillColor, strokeColor, vertexes, imageData);
                    platform.Load(_loader);
                    platformsToLoad.Add(platform);
                }

                maxMapX = Math.Max(maxMapX, x + w);
                maxMapY = Math.Max(maxMapY, y + h);
            }

            Debug.WriteLine($"Map size in px: {maxMapX} x {maxMapY}");

            // setup chunks
            chunkMap.Reset(chunkWidth: 100, chunkHeight: 100, mapWidth: maxMapX, mapHeight: maxMapY);

            // physics reset
            var phys = new MapPhysics(chunkMap, physSettings);

            foreach (var platform in platformsToLoad)
            {
                if (!GameObjects.Contains(platform))
                {
                    GameObjects.Add(platform);
                }

                chunkMap.UpdateEntity(platform);
            }

            // Verify that the level has a beginning and an end.
            if (playerStart == Vector2.Zero)
            {
                throw new NotSupportedException("A level must have a starting point.");
            }
            if (playerExit == Vector2.Zero)
            {
                throw new NotSupportedException("A level must have an exit.");
            }

            // Set player position for new map
            player.Props.Position = playerStart;

            addCoinToLevel(new Vector2(300, 0));

            // Add end point
            addDoorToLevel(playerExit);
        }
Beispiel #38
0
 /// <summary>
 /// Initialises a new instance of an <see cref="SvgElementIdManager"/>.
 /// </summary>
 /// <param name="document">The <see cref="SvgDocument"/> containing the <see cref="SvgElement"/>s to manage.</param>
 public SvgElementIdManager(SvgDocument document)
 {
     this._document = document;
     this._idValueMap = new Dictionary<string, SvgElement>();
 }
Beispiel #39
0
        /// <summary>
        /// Gets the image.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public static BitmapSource GetImage(string name)
        {
            var fileName = GetResourceFile(string.Format(@"{0}.svg", name));

            return(SvgDocument.Open(fileName).Draw().ToImageSource());
        }
Beispiel #40
0
        public static object ValidateFontFamily(string fontFamilyList, SvgDocument doc)
        {
            // Split font family list on "," and then trim start and end spaces and quotes.
            var fontParts = (fontFamilyList ?? "").Split(new[] { ',' }).Select(fontName => fontName.Trim(new[] { '"', ' ', '\'' }));
            var families = System.Drawing.FontFamily.Families;
            FontFamily family;
            IEnumerable<SvgFontFace> sFaces;

            // Find a the first font that exists in the list of installed font families.
            //styles from IE get sent through as lowercase.
            foreach (var f in fontParts)
            {
                if (doc.FontDefns().TryGetValue(f, out sFaces)) return sFaces;

                family = families.FirstOrDefault(ff => ff.Name.ToLower() == f.ToLower());
                if (family != null) return family;

                switch (f)
                {
                    case "serif":
                        return System.Drawing.FontFamily.GenericSerif;
                    case "sans-serif":
                        return System.Drawing.FontFamily.GenericSansSerif;
                    case "monospace":
                        return System.Drawing.FontFamily.GenericMonospace;
                }
            }

            // No valid font family found from the list requested.
            return System.Drawing.FontFamily.GenericSansSerif;
        }
Beispiel #41
0
 private void RenderSvg(SvgDocument svgDoc)
 {
     svgImage.Image = svgDoc.Draw();
 }
Beispiel #42
0
        private void RenderUseElement(ISvgElement svgElement)
        {
            SvgUseElement useElement = (SvgUseElement)svgElement;

            int hashCode = 0; // useElement.OuterXml.GetHashCode();

            if (!this.BeginUseElement(useElement, out hashCode))
            {
                return;
            }

            SvgDocument document = useElement.OwnerDocument;

            XmlElement refEl = useElement.ReferencedElement;

            if (refEl == null)
            {
                this.EndUseElement(useElement, hashCode);
                return;
            }
            XmlElement refElParent = refEl.ParentNode as XmlElement;
            var        siblingNode = refEl.PreviousSibling;

            if (siblingNode != null && siblingNode.NodeType == XmlNodeType.Whitespace)
            {
                siblingNode = siblingNode.PreviousSibling;
            }

            // For the external node, the documents are different, and we may not be
            // able to insert this node, so we first import it...
            if (useElement.OwnerDocument != refEl.OwnerDocument)
            {
                var importedNode = useElement.OwnerDocument.ImportNode(refEl, true) as XmlElement;

                if (importedNode != null)
                {
                    var importedSvgElement = importedNode as SvgElement;
                    if (importedSvgElement != null)
                    {
                        importedSvgElement.Imported       = true;
                        importedSvgElement.ImportNode     = refEl as SvgElement;
                        importedSvgElement.ImportDocument = refEl.OwnerDocument as SvgDocument;
                    }

                    refEl = importedNode;
                }
            }
            else
            {
                // For elements/nodes within the same document, clone it.
                refEl = (XmlElement)refEl.CloneNode(true);
            }
            // Reset any ID on the cloned/copied element to avoid duplication of IDs.
            //           refEl.SetAttribute("id", "");

            useElement.OwnerDocument.Static = true;
            useElement.CopyToReferencedElement(refEl);

            XmlElement refSiblingEl = null;
            string     useId        = null;

            // Compensate for the parent's class and sibling css loss from cloning...
            if (refElParent != null && refElParent.HasAttribute("class"))
            {
                var parentClass = refElParent.GetAttribute("class");
                if (!string.IsNullOrWhiteSpace(parentClass))
                {
                    var parentEl = document.CreateElement(refElParent.LocalName);
                    parentEl.SetAttribute("class", parentClass);

                    parentEl.AppendChild(refEl);

                    refEl = parentEl;
                }
            }
            else if (refElParent != null && siblingNode != null)
            {
                var siblingEl = siblingNode as XmlElement;
                if (siblingEl != null && siblingEl.HasAttribute("class"))
                {
                    var siblingClass = siblingEl.GetAttribute("class");
                    if (!string.IsNullOrWhiteSpace(siblingClass))
                    {
                        refSiblingEl = (XmlElement)siblingEl.CloneNode(true);

                        useElement.AppendChild(refSiblingEl);
                    }
                }
            }
            else
            {
                //useId = useElement.Id;
                //useElement.SetAttribute("id", "");
            }

            useElement.AppendChild(refEl);

            // Now, render the use element...
            this.RenderElement(svgElement);

            if (refSiblingEl != null)
            {
                useElement.RemoveChild(refSiblingEl);
            }
            useElement.RemoveChild(refEl);
            useElement.RestoreReferencedElement(refEl);

            if (useId != null)
            {
                useElement.SetAttribute("id", useId);
            }

            this.EndUseElement(useElement, hashCode);
        }
Beispiel #43
0
        /// <summary>
        /// Gets the element image in function of his status.
        /// </summary>
        /// <param name="element">Element.</param>
        /// <param name="status">A value indicating if the image must be represented in design mode or working mode.</param>
        /// <returns>An image representing the element and all his properties.</returns>
        public Image GetElementImage(Element element, int status)
        {
            string imgKey   = null;
            string cacheKey = null;
            Image  image    = null;

            try
            {
                imgKey   = this.GetResourceName(element, status);
                cacheKey = string.Format("{0}_{1}",
                                         imgKey,
                                         (int)element.Rotation);

                if (this.ImageCache.ContainsKey(cacheKey))
                {
                    image = this.ImageCache[cacheKey];
                }
                else
                {
                    ResourceManager rm = new ResourceManager("Rwm.Otc.Themes.Properties.Resources",
                                                             Assembly.GetExecutingAssembly());

                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(rm.GetString(imgKey));

                    SvgDocument svg = SvgDocument.Open(xml);

                    if ((int)element.Rotation > 0)
                    {
                        SvgRotate rotation = new SvgRotate((int)element.Rotation * 90.0f,
                                                           (float)svg.Height / 2.0f,
                                                           (float)svg.Width / 2.0f);
                        svg.Transforms.Add(rotation);
                    }

                    image = (Image)svg.Draw();

                    this.ImageCache.Add(cacheKey, image);
                }

                // Print the train name into the block
                if (element.Properties.IsBlock && element.IsBlockOccupied)
                {
                    Image imageClone = (Image)image.Clone();

                    using (Graphics g = Graphics.FromImage(imageClone))
                        using (Font font = new Font("Calibri", 10))
                        {
                            g.DrawString(element.Train.Name, font, Brushes.Black, 3, 3);
                        }

                    return(imageClone);
                }

                return(image);
            }
            catch (Exception ex)
            {
                Logger.LogError(this, ex);

                return(Properties.Resources.ICO_IMAGE_ERROR_32);
            }
        }
Beispiel #44
0
        public void TestArrowCodeCreation()
        {
            // Sample code from Issue 212. Thanks to podostro.
            const int width  = 50;
            const int height = 50;

            var document = new SvgDocument()
            {
                ID      = "svgMap",
                ViewBox = new SvgViewBox(0, 0, width, height)
            };

            var defsElement = new SvgDefinitionList()
            {
                ID = "defsMap"
            };

            document.Children.Add(defsElement);

            var groupElement = new SvgGroup()
            {
                ID = "gMap"
            };

            document.Children.Add(groupElement);

            var arrowPath = new SvgPath()
            {
                ID       = "pathMarkerArrow",
                Fill     = new SvgColourServer(Color.Black),
                PathData = SvgPathBuilder.Parse(@"M0,0 L4,2 L0,4 L1,2 z")
            };

            var arrowMarker = new SvgMarker()
            {
                ID           = "markerArrow",
                MarkerUnits  = SvgMarkerUnits.StrokeWidth,
                MarkerWidth  = 5,
                MarkerHeight = 5,
                RefX         = 3,
                RefY         = 2,
                Orient       = new SvgOrient()
                {
                    IsAuto = true
                },
                Children = { arrowPath }
            };

            defsElement.Children.Add(arrowMarker);

            var line = new SvgLine()
            {
                ID          = "lineLinkedPoint",
                StartX      = 0,
                StartY      = 15,
                EndX        = 35,
                EndY        = 35,
                Stroke      = new SvgColourServer(Color.Black),
                StrokeWidth = 3,
                MarkerEnd   = new Uri(string.Format("url(#{0})", arrowMarker.ID), UriKind.Relative)
            };

            groupElement.Children.Add(line);

            var svgXml = document.GetXML();
            var img    = document.Draw();

            var file = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            File.WriteAllText(file + ".svg", svgXml);
            img.Save(file + ".png");
            Debug.WriteLine(string.Format("Svg saved to '{0}'", file));

            // Remove
            var svg = new FileInfo(file + ".svg");

            if (svg.Exists)
            {
                svg.Delete();
            }
            var png = new FileInfo(file + ".png");

            if (png.Exists)
            {
                png.Delete();
            }
        }
Beispiel #45
0
        private void LoadDocument(string fileName, bool loadDefault)
        {
            try
            {
                using (RasterCodecs codecs = new RasterCodecs())
                {
                    // Set load resolution
                    codecs.Options.RasterizeDocument.Load.XResolution = 300;
                    codecs.Options.RasterizeDocument.Load.YResolution = 300;

                    int firstPage = 1;
                    int lastPage  = 1;
                    List <SvgDocument> documents = new List <SvgDocument>();

                    if (!loadDefault)
                    {
                        // Check if the file can be loaded as svg
                        bool canLoadSvg = codecs.CanLoadSvg(fileName);
                        using (CodecsImageInfo info = codecs.GetInformation(fileName, true))
                        {
                            if (!canLoadSvg)
                            {
                                // Check if the file type is not PDF
                                if (info.Format != RasterImageFormat.PdfLeadMrc &&
                                    info.Format != RasterImageFormat.RasPdf &&
                                    info.Format != RasterImageFormat.RasPdfCmyk &&
                                    info.Format != RasterImageFormat.RasPdfG31Dim &&
                                    info.Format != RasterImageFormat.RasPdfG32Dim &&
                                    info.Format != RasterImageFormat.RasPdfG4 &&
                                    info.Format != RasterImageFormat.RasPdfJbig2 &&
                                    info.Format != RasterImageFormat.RasPdfJpeg &&
                                    info.Format != RasterImageFormat.RasPdfJpeg411 &&
                                    info.Format != RasterImageFormat.RasPdfJpeg422 &&
                                    info.Format != RasterImageFormat.RasPdfJpx &&
                                    info.Format != RasterImageFormat.RasPdfLzw &&
                                    info.Format != RasterImageFormat.RasPdfLzwCmyk)
                                {
                                    MessageBox.Show("The selected file can't be loaded as an SVG file", "Invalid File Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }
                            }

                            if (info.TotalPages > 1)
                            {
                                using (ImageFileLoaderPagesDialog dlg = new ImageFileLoaderPagesDialog(info.TotalPages, false))
                                {
                                    if (dlg.ShowDialog(this) == DialogResult.Cancel)
                                    {
                                        return;
                                    }

                                    firstPage = dlg.FirstPage;
                                    lastPage  = dlg.LastPage;
                                }
                            }
                        }
                    }

                    using (WaitCursor wait = new WaitCursor())
                    {
                        for (int page = firstPage; page <= lastPage; page++)
                        {
                            SvgDocument svgDoc = codecs.LoadSvg(fileName, page, _loadSvgOptions) as SvgDocument;
                            documents.Add(svgDoc);
                        }

                        SetDocument(fileName, documents, firstPage);
                    }

                    UpdateControls();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, string.Format("Error {0}{1}{2}", ex.GetType().FullName, Environment.NewLine, ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }
Beispiel #46
0
 // Methods
 internal Link(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc)
 {
 }
Beispiel #47
0
        private void Update(EvaluationContext context)
        {
            var filepath = FilePath.GetValue(context);

            if (!File.Exists(filepath))
            {
                return;
            }

            var         centerToBounds = CenterToBounds.GetValue(context);
            var         scaleToBounds  = ScaleToBounds.GetValue(context);
            SvgDocument svgDoc;

            try
            {
                svgDoc = SvgDocument.Open <SvgDocument>(filepath, null);
            }
            catch (Exception e)
            {
                Log.Warning($"Failed to load svg document {filepath}:" + e.Message);
                return;
            }

            var bounds          = new Vector3(svgDoc.Bounds.Size.Width, svgDoc.Bounds.Size.Height, 0);
            var centerOffset    = centerToBounds ? new Vector3(-bounds.X / 2, bounds.Y / 2, 0) : Vector3.Zero;
            var fitBoundsFactor = scaleToBounds ? (2f / bounds.Y) : 1;
            var scale           = Scale.GetValue(context) * fitBoundsFactor;

            GraphicsPath newPath = new GraphicsPath();

            var paths = new List <GraphicsPath>();

            ConvertAllNodesIntoGraphicPaths(svgDoc.Descendants(), paths);
            newPath.Flatten();

            var totalPointCount = 0;

            foreach (var p in paths)
            {
                p.Flatten();
                totalPointCount += p.PointCount + 1;
            }

            if (totalPointCount != _pointListWithSeparator.NumElements)
            {
                _pointListWithSeparator.SetLength(totalPointCount);
            }

            int pointIndex = 0;

            foreach (var path in paths)
            {
                var startIndex = pointIndex;

                for (var pathPointIndex = 0; pathPointIndex < path.PathPoints.Length; pathPointIndex++)
                {
                    var point = path.PathPoints[pathPointIndex];

                    _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Position
                        = (new Vector3(point.X, 1 - point.Y, 0) + centerOffset) * scale;
                    _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].W           = 1;
                    _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Orientation = Quaternion.Identity;
                    //pointIndex++;
                }

                // Calculate normals
                if (path.PathPoints.Length > 1)
                {
                    for (var pathPointIndex = 0; pathPointIndex < path.PathPoints.Length; pathPointIndex++)
                    {
                        if (pathPointIndex == 0)
                        {
                            _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Orientation =
                                RotationFromTwoPositions(_pointListWithSeparator.TypedElements[0].Position,
                                                         _pointListWithSeparator.TypedElements[1].Position);
                        }
                        else if (pathPointIndex == path.PathPoints.Length - 1)
                        {
                            _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Orientation =
                                RotationFromTwoPositions(_pointListWithSeparator.TypedElements[path.PathPoints.Length - 2].Position,
                                                         _pointListWithSeparator.TypedElements[path.PathPoints.Length - 1].Position);
                        }
                        else
                        {
                            _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Orientation =
                                RotationFromTwoPositions(_pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Position,
                                                         _pointListWithSeparator.TypedElements[startIndex + pathPointIndex + 1].Position);
                        }
                        // _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].W = 1;
                        // _pointListWithSeparator.TypedElements[startIndex + pathPointIndex].Orientation = Quaternion.Identity;
                    }
                }

                pointIndex += path.PathPoints.Length;

                _pointListWithSeparator.TypedElements[pointIndex] = Point.Separator();
                pointIndex++;
            }

            ResultList.Value = _pointListWithSeparator;
        }
Beispiel #48
0
 /// <summary>
 ///     Default constructor
 /// </summary>
 /// <param name="stream"></param>
 public SvgBitmap(Stream stream)
 {
     _svgDocument = SvgDocument.Open <SvgDocument>(stream);
     Height       = (int)_svgDocument.ViewBox.Height;
     Width        = (int)_svgDocument.ViewBox.Width;
 }
 public void ClearImages()
 {
     _currentImage = null;
     _images.Clear();
 }
Beispiel #50
0
        /// <summary>
        /// Gets the element image in function of his status.
        /// </summary>
        /// <param name="element">Element.</param>
        /// <param name="designImage">A value indicating if the image must be represented in design mode or working mode.</param>
        /// <returns>An image representing the element and all his properties.</returns>
        public Image GetElementImage(Element element, bool designImage)
        {
            try
            {
                string imgKey   = this.GetResourceName(element, designImage);
                string cacheKey = string.Format("{0}_{1}", imgKey, (int)element.Rotation);

                Image image;
                if (this.ImageCache.ContainsKey(cacheKey))
                {
                    image = this.ImageCache[cacheKey];
                }
                else
                {
                    ResourceManager rm = new ResourceManager("Rwm.Otc.Themes.Properties.Resources",
                                                             Assembly.GetExecutingAssembly());
                    string xmlSource = rm.GetString(imgKey);
                    if (xmlSource == null)
                    {
                        Logger.LogWarning(this, "THEME WARNING: {0} key not supported in current theme {1}", imgKey, this.Name);
                        return(Properties.Resources.ICO_IMAGE_ERROR_32);
                    }

                    xmlSource = xmlSource.Replace("#NAME", element.Name);

                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(xmlSource);

                    SvgDocument svg = SvgDocument.Open(xml);

                    if ((int)element.Rotation > 0)
                    {
                        SvgRotate rotation = new SvgRotate((int)element.Rotation * 90.0f,
                                                           (float)svg.Height / 2.0f,
                                                           (float)svg.Width / 2.0f);
                        svg.Transforms.Add(rotation);
                    }

                    image = (Image)svg.Draw();

                    if (!this.ImageCache.ContainsKey(cacheKey))
                    {
                        this.ImageCache.Add(cacheKey, image);
                    }
                    else
                    {
                        this.ImageCache[cacheKey] = image;
                    }
                }

                // Print the train name into the block
                if (!designImage && element.Properties.IsBlock && element.IsBlockOccupied)
                {
                    Image imageClone = (Image)image.Clone();

                    using (Graphics g = Graphics.FromImage(imageClone))
                        using (Font font = new Font("Calibri", 10, FontStyle.Bold))
                        {
                            g.DrawString(element.Train.Name, font, Brushes.Black, 3, 3);
                        }

                    return(imageClone);
                }
                else if (designImage && element.Properties.IsBlock)
                {
                    Image imageClone = (Image)image.Clone();

                    using (Graphics g = Graphics.FromImage(imageClone))
                        using (Font font = new Font("Calibri", 10, FontStyle.Bold))
                        {
                            g.DrawString(element.DisplayName, font, Brushes.Black, 3, 3);
                        }

                    return(imageClone);
                }

                return(image);
            }
            catch (Exception ex)
            {
                Logger.LogError(this, ex);

                return(Properties.Resources.ICO_IMAGE_ERROR_32);
            }
        }
Beispiel #51
0
        public static Bitmap FromPath(string path)
        {
            if (File.Exists(path))
            {
                byte[]       buffer = null;
                MemoryStream stream = null;
                Bitmap       bitmap = null;

                try
                {
                    using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                    {
                        buffer = new byte[fs.Length];
                        stream = new MemoryStream(buffer);
                        fs.CopyTo(stream);
                        stream.Seek(0, SeekOrigin.Begin);
                    }

                    var imageType = ImageUtils.GetImageType(buffer);
                    switch (imageType)
                    {
                    case ImageType.PNG:
                        bitmap = new Bitmap(stream);
                        break;

                    case ImageType.WEBP:
                        using (var webp = new WebPWrapper.WebP())
                        {
                            bitmap = webp.Decode(buffer);
                        }
                        break;

                    case ImageType.SVG:
                        bitmap = SvgDocument.Open <SvgDocument>(stream).Draw();
                        break;

                    case ImageType.PSD:
                        var psdFile = new System.Drawing.PSD.PsdFile();
                        psdFile.Load(path);
                        bitmap = System.Drawing.PSD.ImageDecoder.DecodeImage(psdFile);
                        break;

                    case ImageType.ICO:
                        using (var icon = new Icon(path))
                        {
                            bitmap = icon.ToBitmap();
                        }
                        break;

                    case ImageType.TGA:
                        using (var reader = new BinaryReader(stream))
                        {
                            var image = new TgaLib.TgaImage(reader);
                            bitmap = image.GetBitmap().ToBitmap();
                        }
                        break;

                    default:
                        bitmap = new Bitmap(stream);
                        break;
                    }

                    return(bitmap);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Dispose();
                    }
                }
            }

            return(null);
        }
        public static SvgDocument GetSvgDoc(string svgFile)
        {
            SvgDocument document = SvgDocument.Open(svgFile);

            return(Resize(document));
        }
Beispiel #53
0
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
            var t = new XmlDocument();
            t.XmlResolver = null; // Don't verify the XML
            t.LoadXml(textBox1.Text.Substring(textBox1.Text.IndexOf("<svg")));
            FSvgDoc = SvgDocument.Open(t);

            pictureBox1.Image = FSvgDoc.Draw();
            IterateKids(FSvgDoc.Children);

            Vector velocity = new Vector(0, 20);
            DateTime dte1, dte2;
            List<SvgCollision.PolygonCollisionResult> collisions;

            //dte1 = DateTime.Now;
            //collisions = SvgCollision.checkForCollision(FSvgDoc.Children, SvgCollision.collisionCheckType.LineCollision, velocity);
            //dte2 = DateTime.Now;
            //Debug.WriteLine((dte2 - dte1).TotalMilliseconds.ToString());
            //foreach (SvgCollision.PolygonCollisionResult col in collisions)
            //{
            //    //Debug.WriteLine(col.collidor.ToString() + " intersects with " + col.collidee.ToString() + "\tIsIntersecting=" + col.IsIntersecting + "\tWillIntersect=" + col.WillIntersect + "\tOnPath=" + col.OnPath);
            //}

            //dte1 = DateTime.Now;
            //collisions = SvgCollision.checkForCollision(FSvgDoc.Children, SvgCollision.collisionCheckType.SeparatingAxisTheorem, velocity);
            //dte2 = DateTime.Now;
            //Debug.WriteLine((dte2 - dte1).TotalMilliseconds.ToString());
            //foreach (SvgCollision.PolygonCollisionResult col in collisions)
            //{
            //    //Debug.WriteLine(col.collidor.ToString() + " intersects with " + col.collidee.ToString() + "\tIsIntersecting=" + col.IsIntersecting + "\tWillIntersect=" + col.WillIntersect + "\tOnPath=" + col.OnPath);
            //}

            dte1 = DateTime.Now;
            collisions = SvgCollision.checkForCollision(FSvgDoc.Children, SvgCollision.collisionCheckType.Mixed,0, velocity);
            dte2 = DateTime.Now;
            Debug.WriteLine((dte2 - dte1).TotalMilliseconds.ToString() + "\t" + collisions.Count + " collisions found");

            foreach (SvgCollision.PolygonCollisionResult col in collisions)
            {
                Debug.WriteLine(col.collidor.ToString() + " intersects with " + col.collidee.ToString() + "\tIsIntersecting=" + col.IsIntersecting + "\tWillIntersect=" +
                    col.WillIntersect + "\tOnPath=" + col.OnPath + "\tRayCasting=" + col.rayCastingResult + "\tMinVector=" + col.MinimumTranslationVector.X + "," + col.MinimumTranslationVector.Y   );
            }
            }
            catch { }

            //drawCirclePath(FSvgDoc.Children);
        }
Beispiel #54
0
        private async void WorldMap_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // Disables the default mouse double-click action.
            e.Handled = true;

            // Determin the location to place the pushpin at on the map.

            //Get the mouse click coordinates
            Point mousePosition = e.GetPosition(stackPanelMap);
            //Convert the mouse coordinates to a locatoin on the map
            Location pinLocation = worldMap.ViewportPointToLocation(mousePosition);

            string baseURL    = "http://dev.virtualearth.net";
            string controller = string.Format("/REST/v1/Locations/{0}?inclnb=1&incl=ciso2&key={1}", pinLocation.Latitude.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture) + "," + pinLocation.Longitude.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture), "Aq3R2llqn0c86NeqB - LbOwxVC8hodxNHBckFcfnxDFUA5MvYUU0CGClXctL6VTdX");

            Response response = await LocationAPIService.GetLocation(baseURL, controller);

            LocationResponse locationResponse = (LocationResponse)response.Result;

            try
            {
                string isoCode = locationResponse.ResourceSets[0].Resources[0].Address.CountryRegionIso2;

                Country countryCode = new Country();

                foreach (var country in countries)
                {
                    if (country.Alpha2Code == isoCode)
                    {
                        countryCode = country;
                    }
                }

                if (countryCode == null)
                {
                    dialogService.ShowMessage("Error", "Could not find a macth");
                }
                else
                {
                    lbl_countryName.Content       = MissInfo(countryCode.Name);
                    lbl_countryCapital.Content    = MissInfo(countryCode.Capital);
                    lbl_countryPopulation.Content = MissInfo(countryCode.Population.ToString());
                    lbl_regiao.Content            = MissInfo(countryCode.Region);
                    lbl_subRegion.Content         = MissInfo(countryCode.Subregion);
                    lbl_gini.Content            = MissInfo(countryCode.Gini.ToString());
                    list_currencies.ItemsSource = countryCode.Currencies;
                    lbl_symbol.Content          = string.Empty;
                    foreach (var currency in countryCode.Currencies)
                    {
                        lbl_symbol.Content += currency.Symbol;
                    }

                    try
                    {
                        imgFlags.Source = Bitmap2BitmapImage(SvgDocument.Open($@"Data\imgs\{countryCode.Alpha2Code}.svg").Draw());
                    }
                    catch (Exception)
                    {
                        dialogService.ShowMessage("Error", "Flag not found");
                        string fileName = $"{Environment.CurrentDirectory}\\Data\\Imgs\\Default.svg";
                        imgFlags.Source = Bitmap2BitmapImage(SvgDocument.Open(fileName).Draw());
                    }
                }
                txt_search.Text = string.Empty;
            }
            catch (Exception ex)
            {
                dialogService.ShowMessage("Error", ex.Message);
            }
        }
        protected virtual void Load()
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(_svgSource))
                {
                    // Load the source
                    _svgWindow.Source = _svgSource;
                    // Initialize the style sheets
                    SetupStyleSheets();
                    // Execute all script elements
                    //UnloadEngines();
                    //InitializeEvents();
                    //ExecuteScripts();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (!string.IsNullOrWhiteSpace(_xmlSource) && _xmlSource.Length > ValidSVG.Length)
                {
                    SvgDocument doc = _svgWindow.CreateEmptySvgDocument();
                    doc.LoadXml(_xmlSource);
                    _svgWindow.Document = doc;

                    SetupStyleSheets();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }
                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (_uriSource != null)
                {
                    // Load the source
                    _svgWindow.Source = _uriSource.AbsoluteUri;
                    // Initialize the style sheets
                    SetupStyleSheets();
                    // Execute all script elements
                    //UnloadEngines();
                    //InitializeEvents();
                    //ExecuteScripts();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
                else if (_streamSource != null)
                {
                    SvgDocument doc = _svgWindow.CreateEmptySvgDocument();
                    doc.Load(_streamSource);
                    _svgWindow.Document = doc;

                    SetupStyleSheets();

                    SvgSvgElement svgEl = (SvgSvgElement)_svgWindow.Document.RootElement;
                    SvgSizeF      r     = svgEl.GetSize();

                    int winWidth  = (int)svgEl.Width.BaseVal.Value;
                    int winHeight = (int)svgEl.Height.BaseVal.Value;
                    if (!r.Width.Equals(0.0) && !r.Height.Equals(0.0) && (r.Width * 4 * r.Height) < BitmapLimit)
                    {
                        winWidth  = (int)r.Width;
                        winHeight = (int)r.Height;
                    }
                    if ((winWidth * 4 * winHeight) >= BitmapLimit)
                    {
                        winWidth  = this.Width;
                        winHeight = this.Height;
                    }

                    _svgWindow.Resize(winWidth, winHeight);

                    _svgRenderer.InvalidRect = SvgRectF.Empty;

                    this.Render();
                    _isSvgLoaded = true;
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());

                if (this.DesignMode)
                {
                    return;
                }
                var errorArgs = new SvgErrorArgs("An error occurred while loading the document", ex);
                _svgErrors?.Invoke(this, errorArgs);
                if (!errorArgs.Handled)
                {
                    MessageBox.Show(errorArgs.Message + ": " + ex.Message,
                                    _appTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 public SvgFrame(SvgDocument svg)
 {
     this.svg = svg;
 }
Beispiel #57
0
        public static void SetStation(string name, string signal, string logoPath = null)
        {
            try
            {
                if (Settings.Overlay)
                {
                    int width = 0, height = 0;
                    GPSI_GetScreenSize(ref width, ref height);
                    System.Threading.Thread.Sleep(10);
                    GPSI_GetScreenSize(ref width, ref height);

                    if (width == 0 || height == 0)
                    {
                        width  = Screen.PrimaryScreen.WorkingArea.Width;
                        height = Screen.PrimaryScreen.WorkingArea.Height;
                    }

                    //GPSL_SetTextLineData(0, 10, 10, name, Color.FromArgb(255, 174, 0).ToArgb(), false, 25, true, 0);
                    //GPSL_ShowText(0, true);

                    Image bmp = new Bitmap(Resources.overlay_double);

                    RectangleF rectf = new RectangleF(0, 0, bmp.Width, bmp.Height);

                    Graphics g = Graphics.FromImage(bmp);

                    if (Settings.VR)
                    {
                        g.TranslateTransform(0, bmp.Height);
                        g.ScaleTransform(1, -1);
                    }

                    //g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    g.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                    g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;

                    StringFormat format = new StringFormat()
                    {
                        Alignment     = StringAlignment.Center,
                        LineAlignment = StringAlignment.Center
                    };
                    var font = new Font("Microsoft Sans Serif", 15, FontStyle.Bold);

                    var stringSize     = g.MeasureString(NowPlaying + " " + name, font);
                    var nowPlayingSize = g.MeasureString(NowPlaying + " ", font);
                    var nameSize       = g.MeasureString(name, font);
                    var topLeft        = new PointF((512 / 2) - (stringSize.Width / 2) + 123,
                                                    (bmp.Height / 2) - (stringSize.Height / 2));
                    //var rectangle = new Rectangle(0, 0, (int)stringSize.Width, (int)stringSize.Height);
                    var brush = new SolidBrush(Color.FromArgb(255, 174, 0));
                    //var brush = new LinearGradientBrush(rectangle, Color.White, Color.FromArgb(255, 174, 0), 0.0f, false);
                    if (RTL)
                    {
                        g.DrawString(name, font, brush, topLeft);
                        g.DrawString(NowPlaying, font, Brushes.White, new PointF(topLeft.X + nameSize.Width + nowPlayingSize.Width, topLeft.Y), new StringFormat {
                            FormatFlags = StringFormatFlags.DirectionRightToLeft
                        });
                    }
                    else
                    {
                        g.DrawString(name, font, brush, new PointF(topLeft.X + nowPlayingSize.Width, topLeft.Y));
                        g.DrawString(NowPlaying, font, Brushes.White, topLeft);
                    }

                    switch (signal)
                    {
                    case "0":
                        g.DrawImage(Resources.signal_0, 593, bmp.Height - 36, 32, 32);
                        break;

                    case "1":
                        g.DrawImage(Resources.signal_1, 593, bmp.Height - 36, 32, 32);
                        break;

                    case "2":
                        g.DrawImage(Resources.signal_2, 593, bmp.Height - 36, 32, 32);
                        break;

                    case "3":
                        g.DrawImage(Resources.signal_3, 593, bmp.Height - 36, 32, 32);
                        break;

                    case "4":
                        g.DrawImage(Resources.signal_4, 593, bmp.Height - 36, 32, 32);
                        break;

                    case "5":
                        g.DrawImage(Resources.signal_5, 593, bmp.Height - 36, 32, 32);
                        break;
                    }
                    if (logoPath != null)
                    {
                        if (logoPath.StartsWith("http"))
                        {
                            using (var client = new WebClient())
                            {
                                var newPath = Directory.GetCurrentDirectory() + "\\tmp" + Path.GetExtension(logoPath);
                                client.DownloadFile(logoPath, newPath);
                                logoPath = newPath;
                            }
                        }
                        else
                        {
                            logoPath = Directory.GetCurrentDirectory() +
                                       @"\web\" + logoPath.Replace("/", "\\");
                        }
                        //var logo = Image.FromFile(Directory.GetCurrentDirectory() + @"\web\stations\images-america\tucson\La Caliente.png");
                        //MessageBox.Show(Directory.GetCurrentDirectory() +
                        //                @"\web\" + logoPath.Replace("/", "\\"));
                        try
                        {
                            if (logoPath.EndsWith("svg"))
                            {
                                try
                                {
                                    var img = SvgDocument.Open(logoPath);
                                    logoPath = logoPath.Replace(".svg", ".png");
                                    using (Bitmap tempImage = new Bitmap(img.Draw()))
                                    {
                                        tempImage.Save(logoPath);
                                    }
                                    //img.Save(logoPath, ImageFormat.Png);
                                }
                                catch (Exception)
                                {
                                    logoPath = logoPath.Replace(".svg", ".png");
                                }
                            }

                            var logo = new Bitmap(logoPath);

                            var logoHeight = (float)logo.Height;
                            var logoWidth  = (float)logo.Width;
                            if (logoHeight > 0.41f * logoWidth)
                            {
                                logoWidth  = (float)((90f / logoHeight) * logoWidth);
                                logoHeight = 90;
                            }
                            else if (logoHeight <= 0.41f * logoWidth)
                            {
                                logoHeight = (float)((220f / logoWidth) * logoHeight);
                                logoWidth  = 220;
                            }

                            //MessageBox.Show("bmpw: " + bmp.Width + "; bmph: " + bmp.Height + "; logow: " + logoWidth.ToString() + "; logoh: " + logoHeight.ToString());

                            g.DrawImage(logo, (256 / 2) - (logoWidth / 2) + 645, (bmp.Height / 2) - (logoHeight / 2), logoWidth,
                                        logoHeight);
                        }
                        catch (Exception ex)
                        {
                            Log.Write(logoPath);
                            Log.Write(ex.ToString());
                        }
                    }

                    g.Flush();

                    //TODO: Get memory picture to work.
                    //MemoryStream ms = new MemoryStream();
                    //bmp.Save(ms, ImageFormat.Png);

                    //GPPICI_LoadNewInternalPicture(ms.ToArray(), (int) ms.Length);
                    //GPPICI_ShowInternalPicturePos(true, (width/2) - (Resources.overlay.Width/2), (height/4));

                    bmp.Save(Directory.GetCurrentDirectory() + @"\overlay.png");

                    GPPIC_LoadNewPicture(Directory.GetCurrentDirectory() + @"\overlay.png");
                    GPPIC_ShowPicturePos(true, (width / 2) - (bmp.Width / 2), (height / 4));

                    Timer.Interval = 4000;
                    Timer.Elapsed += (sender, args) =>
                    {
                        Timer.Enabled = false;
                        Timer.Stop();
                        GPPIC_ShowPicturePos(false, (width / 2) - (Resources.overlay.Width / 2), (height / 4));
                        //GPPICI_ShowInternalPicturePos(false, (width/2) - (Resources.overlay.Width/2), (height/4));
                        //Log.Write("Hide overlay");
                    };
                    Timer.Enabled = true;
                    Timer.Start();
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex.ToString());
            }
        }
Beispiel #58
0
        private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            //render svg
            var fileName = lstFiles.SelectedItem.ToString();
            if (fileName.StartsWith("#")) return;
            
            //display png
            var png = Image.FromFile(_pngBasePath + Path.GetFileNameWithoutExtension(fileName) + ".png");
            picPng.Image = png;
            
            var doc = new SvgDocument();
            try
            {
                Debug.Print(fileName);
                doc = SvgDocument.Open(_svgBasePath + fileName);
                if (fileName.StartsWith("__"))
                {
                    picSvg.Image = doc.Draw();
                }
                else
                {
                    var img = new Bitmap(480, 360);
                    doc.Draw(img);
                    picSvg.Image = img;

                }

				this.boxConsoleLog.AppendText ("\n\nWC3 TEST " + fileName + "\n");

            }
            catch (Exception ex)
            {
				this.boxConsoleLog.AppendText ("Result: TEST FAILED\n");
				this.boxConsoleLog.AppendText ("SVG RENDERING ERROR for " + fileName + "\n");
				this.boxConsoleLog.AppendText (ex.ToString());
                //MessageBox.Show(ex.ToString(), "SVG Rendering");
                picSvg.Image = null;
            }
            
            //save load
            try 
            {
                using(var memStream = new MemoryStream())
                {
                    doc.Write(memStream);
                    memStream.Position = 0;  
                    var reader = new StreamReader(memStream);
                    var tempFilePath = Path.Combine(Path.GetTempPath(), "test.svg");
                    System.IO.File.WriteAllText(tempFilePath, reader.ReadToEnd());
                    memStream.Position = 0;
                    var baseUri = doc.BaseUri;
                    doc = SvgDocument.Open(tempFilePath);
                    doc.BaseUri = baseUri;
                    
                    if (fileName.StartsWith("__"))
                    {
                        picSaveLoad.Image = doc.Draw();
                    }
                    else
                    {
                        var img = new Bitmap(480, 360);
                        doc.Draw(img);
                        picSaveLoad.Image = img;
                    }
                }
            } 
            catch (Exception ex)
            {
				this.boxConsoleLog.AppendText ("Result: TEST FAILED\n");
				this.boxConsoleLog.AppendText ("SVG SERIALIZATION ERROR for " + fileName + "\n");
				this.boxConsoleLog.AppendText (ex.ToString());
                //MessageBox.Show(ex.ToString(), "SVG Serialization");
                picSaveLoad.Image = null;
            }
            
            //compare svg to png
            try
            {
                picSVGPNG.Image = PixelDiff((Bitmap)picPng.Image, (Bitmap)picSvg.Image);
            }
            catch (Exception ex)
            {
				this.boxConsoleLog.AppendText ("Result: TEST FAILED\n");
				this.boxConsoleLog.AppendText ("SVG TO PNG COMPARISON ERROR for " + fileName + "\n");
				this.boxConsoleLog.AppendText (ex.ToString());
                //MessageBox.Show(ex.ToString(), "SVG Comparison");
                picSVGPNG.Image = null;
            }



            
           
        }
Beispiel #59
-1
 private void RenderSvg(SvgDocument svgDoc)
 {
     //var render = new DebugRenderer();
     //svgDoc.Draw(render);
     svgImage.Image = svgDoc.Draw();
     svgImage.Image.Save(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(svgDoc.BaseUri.LocalPath), "output.png"));
 }
        private static SvgElement CreateElement(XmlTextReader reader, bool fragmentIsDocument, SvgDocument document)
        {
            SvgElement createdElement = null;
            string elementName = reader.LocalName;

            //Trace.TraceInformation("Begin CreateElement: {0}", elementName);

            if (elementName == "svg")
            {
                createdElement = (fragmentIsDocument) ? new SvgDocument() : new SvgFragment();
            }
            else
            {
                ElementInfo validType = AvailableElements.SingleOrDefault(e => e.ElementName == elementName);
                if (validType != null)
                {
                    createdElement = (SvgElement)Activator.CreateInstance(validType.ElementType);
                }
            }

            if (createdElement != null)
            {
                createdElement.ElementName = elementName;
                SetAttributes(createdElement, reader, document);
            }

            //Trace.TraceInformation("End CreateElement");

            return createdElement;
        }