示例#1
0
        public void LoadSvg(XmlDocument document, SizeF?size = null)
        {
            var defaultSize = new SizeF(MinDimension, MinDimension);

            if (document != null)
            {
                _svgDoc = SvgLib.SvgDocument.Open(document);

                if (_svgDoc.Width > 0 && _svgDoc.Height > 0)
                {
                    defaultSize.Width  = _svgDoc.Width;
                    defaultSize.Height = _svgDoc.Height;
                }

                _strokeColor = System.Drawing.Color.Empty;
                var color = GetStrokeColorFromSvg(_svgDoc);
                if (!color.IsEmpty)
                {
                    _strokeColor = new RgbColor(color);
                }

                UpdateStrokeColor();
            }

            if (size.HasValue)
            {
                defaultSize = size.Value;
            }

            ChangeControlPoints(null, null, ControlPoints[0].X + defaultSize.Width, ControlPoints[0].Y + defaultSize.Height);
        }
示例#2
0
        public void resetFarbe()                                        //Methode zum reseten der Farben
        {
            String dateiPfad = Application.StartupPath + "/Europa.svg"; //Pfad der Svg einlesen

            StreamReader dateiLeser = File.OpenText(dateiPfad);         // die Datei öffnen

            string[] Datei = new string[150];                           // eine Array für die Zeilen erstellen
            int      a     = 0;

            while (!dateiLeser.EndOfStream)           // bis zum Ende der Datei ...
            {
                string zeile = dateiLeser.ReadLine(); // ... die nächste Zeile lesen und in einen String schreiben und ...
                Datei[a] = zeile;                     //Zeilen in das Array schreiben
                a++;
            }


            dateiLeser.Close();

            //Fülle neue Svg-Datei mit dem Array
            StreamWriter outputStreamWriter = File.CreateText(Application.StartupPath + @"/Europa(gefärbt).svg");        //Erstelle oder überschreibe die neuen Svg

            for (int i = 0; i < 150; i++)
            {
                outputStreamWriter.WriteLine(Datei[i]);
            }
            outputStreamWriter.Close();

            //Füge die neue Svg-Datei in die Picturebox(SvgImage) ein
            SVGParser.MaximumSize = new Size(SvgImage.Width, SvgImage.Height);
            selectedPath          = Application.StartupPath + @"/Europa(gefärbt).svg";
            svgDocument           = SVGParser.GetSvgDocument(selectedPath);
            SvgImage.Image        = SVGParser.GetBitmapFromSVG(selectedPath);
        }
示例#3
0
        public GlassSelector()
        {
            Stream stream = GetSvgStreem();

            SvgOrigin = SvgDocument.Open <SvgDocument>(stream);
            AddEvents((int)Gdk.EventMask.PointerMotionMask);
        }
示例#4
0
        public static void Generate(DegradomeType dType, int length, int index)
        {
            string dotBracket = GetStruct(dType, length, index);
            string outputFile = RnaPlotWrapper.Plot(dotBracket);

            File.Copy(outputFile, $"{Config.WorkingFolder}\\cs_rna_struct\\plot\\{dType}_{length}_{index}.svg");
            Svg.SvgDocument doc = SvgDocument.Open(outputFile);
            doc.Draw().Save($"{Config.WorkingFolder}\\cs_rna_struct\\plot\\{dType}_{length}_{index}.png");
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         string          tSvg     = Request["svg"];
         string          fileName = Request["unitId"];
         MemoryStream    tData    = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));
         Svg.SvgDocument tSvgObj  = SvgDocument.Open(tData);
         tSvgObj.Draw().Save("e:\\" + fileName + ".png", ImageFormat.Png);
     }
 }
示例#6
0
 private void btnGuardar_Click(object sender, EventArgs e)
 {
     if (ValidarForm())
     {
         SVGParser.SizeInicio = new Size(pickImagen.Width, pickImagen.Height);
         svgDocument          = SVGParser.GetSvgDocument(selectedPath);
         nupAncho.Value       = (int)svgDocument.Width.Value;
         nupAlto.Value        = (int)svgDocument.Height.Value;
         pickImagen.Image     = SVGParser.GetBitmapFromSVG(selectedPath);
     }
 }
示例#7
0
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult selectResult = filePicker.ShowDialog();

            if (selectResult == System.Windows.Forms.DialogResult.OK)
            {
                Svg.SVGParser.MaximumSize = new Size(pictConvertedImage.Width, pictConvertedImage.Height);

                selectedPath = filePicker.FileName;

                svgDocument = Svg.SVGParser.GetSvgDocument(selectedPath);

                pictConvertedImage.Image = Svg.SVGParser.GetBitmapFromSVG(selectedPath);
            }
        }
示例#8
0
        private void btnBuscar_Click(object sender, EventArgs e)
        {
            DialogResult selectResult = filePicker.ShowDialog();

            if (selectResult == System.Windows.Forms.DialogResult.OK)
            {
                SVGParser.SizeInicio = new Size(pickImagen.Width, pickImagen.Height);
                selectedPath         = filePicker.FileName;
                txtBuscar.Text       = selectedPath;
                svgDocument          = SVGParser.GetSvgDocument(selectedPath);
                nupAncho.Value       = (int)svgDocument.Width.Value;
                nupAlto.Value        = (int)svgDocument.Height.Value;
                pickImagen.Image     = SVGParser.GetBitmapFromSVG(selectedPath);
                Guardar.FileName     = filePicker.FileName;
            }
        }
示例#9
0
        public static void SavePng(string tSvg, string tFileName)
        {
            MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));

            Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
            MemoryStream    tStream = new MemoryStream();

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

            using (Stream localFile = new FileStream(tFileName,
                                                     FileMode.OpenOrCreate))

            {
                localFile.Write(tStream.ToArray(), 0, (int)tStream.Length);
            }
        }
示例#10
0
        public void export_png(String tSvg)
        {
            string       tFileName = "chart";
            string       tType     = "image/png";
            MemoryStream tData     = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));
            MemoryStream tStream   = new MemoryStream();
            string       tExt      = "png";

            try {
                Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
                tSvgObj.Draw().Save("D:\\PSOG.UI\\chart.bmp", ImageFormat.Bmp);
            }
            catch (Exception e) {
                System.Console.WriteLine(e);
            }
        }
示例#11
0
        private void Einfärben(int farbeAlt, int farbeNeu, int LandID)           //Methode zum einfärben
        {
            String dateiPfad = Application.StartupPath + "/Europa(gefärbt).svg"; //Pfad der Svg einlesen

            StreamReader dateiLeser = File.OpenText(dateiPfad);                  // die Datei öffnen

            string[] Datei = new string[150];                                    // eine Array für die Zeilen erstellen
            int      a     = 0;

            while (!dateiLeser.EndOfStream)           // bis zum Ende der Datei ...
            {
                string zeile = dateiLeser.ReadLine(); // ... die nächste Zeile lesen und in einen String schreiben und ...
                Datei[a] = zeile;                     //Zeilen in das Array schreiben
                a++;
            }


            dateiLeser.Close();

            //Suche nach Nummer des Land und ersetze die Farbe
            for (int i = 0; i < 85; i++)
            {
                bool enthält = Datei[i].Contains($"--{LandID}--");
                if (enthält == true)
                {
                    Datei[i] = Datei[i].Replace($"fil{farbeAlt}", $"fil{farbeNeu}");
                }
            }


            //Fülle neue Svg-Datei mit dem Array
            StreamWriter outputStreamWriter = File.CreateText(Application.StartupPath + @"/Europa(gefärbt).svg");       //Erstelle oder überschreibe die neuen Svg

            for (int i = 0; i < 150; i++)
            {
                outputStreamWriter.WriteLine(Datei[i]);
            }
            outputStreamWriter.Close();

            //Füge die neue Svg-Datei in die Picturebox(SvgImage) ein
            SVGParser.MaximumSize = new Size(SvgImage.Width, SvgImage.Height);
            selectedPath          = Application.StartupPath + @"/Europa(gefärbt).svg";
            svgDocument           = SVGParser.GetSvgDocument(selectedPath);
            SvgImage.Image        = SVGParser.GetBitmapFromSVG(selectedPath);
        }
示例#12
0
        //根据svg生成图片
        void HuiTu(string tSvg, string strImgPath, string strImg)
        {
            strImgPath = System.Web.HttpContext.Current.Server.MapPath(strImgPath);
            if (!Directory.Exists(strImgPath))
            {
                Directory.CreateDirectory(strImgPath);
            }

            MemoryStream tData   = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));
            MemoryStream tStream = new MemoryStream();
            string       tTmp    = new Random().Next().ToString();

            Svg.SvgDocument tSvgObj = SvgDocument.Open(tData);
            tSvgObj.Draw().Save(tStream, ImageFormat.Jpeg);

            FileStream fls = new FileStream(strImgPath, FileMode.Create);//创建文件

            tStream.WriteTo(fls);
            tStream.Close();
            fls.Close();
        }
示例#13
0
 public SvgDeferredPaintServer(SvgDocument document, string id)
 {
     Document   = document;
     DeferredId = id;
 }
示例#14
0
        /// <summary>
        /// Given the SVG/XML fragment return a fully populated SVG node.  The returned node is not added to the given document
        /// </summary>
        /// <param name="document">The document context to parse the in content in</param>
        /// <param name="fragment">The SVG/XML formatted string to parse</param>
        /// <param name="entities">Optional dictionary to resolve entities. May be null.</param>
        /// <returns></returns>
        public SvgElement[] ParseFragment(SvgDocument document, string fragment, Dictionary <string, string> entities)
        {
            NameTable           nt    = new NameTable();
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt);

            nsmgr.AddNamespace("svg", svgNS);

            XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None);

            using (var reader = new SvgTextReader(fragment, XmlNodeType.Element, context, entities))
            {
                var        elements     = new List <SvgElement>();
                var        elementStack = new Stack <SvgElement>();
                var        value        = new StringBuilder();
                bool       elementEmpty;
                SvgElement element = null;
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:
                        // Does this element have a value or children
                        // (Must do this check here before we progress to another node)
                        elementEmpty = reader.IsEmptyElement;
                        // Create element
                        element = CreateElement(reader, document);

                        // Add to the parents children
                        if (elementStack.Count > 0)
                        {
                            var parent = elementStack.Peek();
                            if (parent != null && element != null)
                            {
                                parent.Children.Add(element);
                            }
                        }
                        else
                        {
                            elements.Add(element);
                        }

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

                        // Need to process if the element is empty
                        if (elementEmpty)
                        {
                            goto case XmlNodeType.EndElement;
                        }

                        break;

                    case XmlNodeType.EndElement:

                        // Pop the element out of the stack
                        element = elementStack.Pop();

                        if (value.Length > 0 && element != null)
                        {
                            element.Content = value.ToString();
                            // Reset content value for new element
                            value.Clear();
                        }
                        break;

                    case XmlNodeType.CDATA:
                    case XmlNodeType.Text:
                        value.Append(reader.Value);
                        break;
                    }
                }
                return(elements.ToArray());
            }
        }
示例#15
0
        public SvgDocument Open(Stream stream, Dictionary <string, string> entities)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            //Trace.TraceInformation("Begin Read");

            using (var reader = new SvgTextReader(stream, entities))
            {
                var         elementStack = new Stack <SvgElement>();
                var         value        = new StringBuilder();
                bool        elementEmpty;
                SvgElement  element = null;
                SvgElement  parent;
                SvgDocument svgDocument = null;
                reader.XmlResolver        = new SvgDtdResolver();
                reader.WhitespaceHandling = WhitespaceHandling.None;

                while (reader.Read())
                {
                    try
                    {
                        switch (reader.NodeType)
                        {
                        case XmlNodeType.Element:
                            // Does this element have a value or children
                            // (Must do this check here before we progress to another node)
                            elementEmpty = reader.IsEmptyElement;
                            // Create element
                            if (elementStack.Count > 0)
                            {
                                element = CreateElement(reader, svgDocument);
                            }
                            else
                            {
                                svgDocument = CreateDocument(reader);
                                element     = svgDocument;
                            }

                            // Add to the parents children
                            if (elementStack.Count > 0)
                            {
                                parent = elementStack.Peek();
                                if (parent != null && element != null)
                                {
                                    parent.Children.Add(element);
                                }
                            }

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

                            // Need to process if the element is empty
                            if (elementEmpty)
                            {
                                goto case XmlNodeType.EndElement;
                            }

                            break;

                        case XmlNodeType.EndElement:

                            // Pop the element out of the stack
                            element = elementStack.Pop();

                            if (value.Length > 0 && element != null)
                            {
                                element.Content = value.ToString();

                                // Reset content value for new element
                                value.Clear();
                            }
                            break;

                        case XmlNodeType.CDATA:
                        case XmlNodeType.Text:
                            value.Append(reader.Value);
                            break;
                        }
                    }
                    catch (Exception exc)
                    {
                        Trace.TraceError(exc.Message);
                    }
                }

                //Trace.TraceInformation("End Read");
                return(svgDocument);
            }
        }
示例#16
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>();
 }
示例#17
0
        /// <summary>
        /// Renders the specified <see cref="HeatMapModel"/>, optionally saves the output SVG
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="filePath">The file path.</param>
        /// <returns></returns>
        public Svg.SvgDocument Render(HeatMapModel model, String filePath = "")
        {
            rangeFinder valueRange = model.DetectMinMax();

            var lColor = style.LowColor.GetColorVersionWithAlpha(style.MinOpacity);  //.ColorToHex();
            var hColor = style.HighColor.GetColorVersionWithAlpha(style.MaxOpacity); //.ColorToHex();



            ColorGradient colorGradient = new ColorGradient(lColor, hColor, ColorGradientFunction.AllAToB);


            cursorZoneSpatialSettings format = style.fieldContainer.GetFormatSetup();

            format.spatialUnit       = 8;
            format.spatialUnitHeight = 10;

            Int32 width  = (model.weight * format.width) + format.margin.right;
            Int32 height = (model.height * format.height) + format.margin.bottom;

            Svg.SvgDocument output = new Svg.SvgDocument
            {
                Width  = width,
                Height = height,
                Ppi    = 100
            };

            var mainContainer = new SvgGroup();

            output.Children.Add(mainContainer);

            //(new SvgLength(width), new SvgLength(height));

            // output.ViewBox = new SvgViewBox(-100, -100, width+100, height+100);

            var group = new SvgGroup();

            mainContainer.Children.Add(group);

            var layerTwo = new SvgGroup();

            mainContainer.Children.Add(layerTwo);

            prepareLabels(model);

            var hor = new SvgGroup();

            if (style.options.HasFlag(HeatMapRenderOptions.addHorizontalLabels))
            {
                layerTwo.Children.Add(hor);
            }

            for (int x = 0; x < model.weight; x++)
            {
                Int32 xStart = x * format.width;

                Svg.SvgText label = xLabels[x].GetSvgText(format, x, -1);

                //Svg.SvgText label = new SvgText(xLabels[x])
                //{
                //    X = (xStart + (format.width / 2) - format.margin.right).Get_px(),
                //    Y = (-format.height / 2).Get_px(),
                //    Color = new SvgColourServer(Color.Black),
                //    Font = "Gulliver"

                //};

                hor.Children.Add(label);

                var vert = new SvgGroup();
                layerTwo.Children.Add(vert);

                var vertLabels = new SvgGroup();
                var vertValues = new SvgGroup();
                var vertScale  = new SvgGroup();

                if (style.options.HasFlag(HeatMapRenderOptions.addVerticalLabels))
                {
                    vert.Children.Add(vertLabels);
                }
                if (style.options.HasFlag(HeatMapRenderOptions.addVerticalValueScale))
                {
                    vert.Children.Add(vertScale);
                }
                if (style.options.HasFlag(HeatMapRenderOptions.addVerticalValueScale))
                {
                    vert.Children.Add(vertValues);
                }

                for (int y = 0; y < model.height; y++)
                {
                    Int32 yStart = y * format.height;

                    if (x == 0)
                    {
                        Double ratio        = valueRange.GetPositionInRange(y); //model.GetRatioForScale(y, style.minimalOpacity, model.height); //(1+ style.minimalOpacity).GetRatio(y+1);
                        Double scaleFactor2 = ratio;
                        if (!style.options.HasFlag(HeatMapRenderOptions.resizeFields))
                        {
                            scaleFactor2 = 1;
                        }

                        if (ratio > 1)
                        {
                            ratio = 1;
                        }
                        var lbl2 = format.GetRectangle((-format.width * 2), yStart, colorGradient.GetColor(ratio), Convert.ToSingle(ratio), scaleFactor2);
                        vertScale.Children.Add(lbl2);

                        Svg.SvgText label2 = yLabels[y].GetSvgText(format, -1, y);
                        vertLabels.Children.Add(label2);

                        //Svg.SvgText label = xLabels[x].GetSvgText(format, x, -1);

                        //Svg.SvgText label2 = new SvgText(yLabels[y])
                        //{
                        //    X = (format.margin.left - format.width).Get_px(),
                        //    Y = (yStart+(format.height / 2)).Get_px(),
                        //    Color = new SvgColourServer(Color.Black),

                        //    Font = "Gulliver"
                        //};

                        Int32 xp = Convert.ToInt32((-Convert.ToDouble(format.width) * 2.5) + format.margin.left);

                        //Double vl = (1.GetRatio(y + 1)) * model.ranger.Maximum;

                        Double vl = model.GetValueForScaleY(y);

                        Svg.SvgText value = vl.ToString(style.valueFormat).GetSvgText(format, -3, y);

                        //Svg.SvgText value = new SvgText()
                        //{
                        //    X = (xp- format.margin.right).Get_px(),
                        //    Y = (yStart + (format.height / 2) ).Get_px(),
                        //    Fill = new SvgColourServer(Color.Black),
                        //   // Color = new SvgColourServer(Color.White),
                        //    Font = "Gulliver"
                        //};

                        vertValues.Children.Add(value);
                    }

                    Double val  = valueRange.GetPositionInRange(model[x, y]); // model.GetRatioValue(x, y, style.minimalOpacity);
                    Color  valC = colorGradient.GetColor(val);


                    Double scaleFactor = val;

                    if (!style.options.HasFlag(HeatMapRenderOptions.resizeFields))
                    {
                        scaleFactor = 1;
                    }
                    var rct = format.GetRectangle(xStart, yStart, valC, Convert.ToSingle(val), scaleFactor);

                    group.Children.Add(rct);
                }
            }

            if (!filePath.isNullOrEmpty())
            {
                if (!filePath.EndsWith(".svg", true, CultureInfo.CurrentCulture))
                {
                    filePath += ".svg";
                }


                output.Save(filePath);

                //  throw new NotImplementedException();

                /* var code = output.GetXML();  //Encoding.UTF8.GetString(stream.GetBuffer());
                 *
                 */
            }

            return(output);
        }
        //Does not update dynamic blocks
        public static void exportblockstosvg()
        {
            DocumentCollection docCol   = Application.DocumentManager;
            Database           localDb  = docCol.MdiActiveDocument.Database;
            Document           doc      = docCol.MdiActiveDocument;
            CivilDocument      civilDoc = Autodesk.Civil.ApplicationServices.CivilApplication.ActiveDocument;

            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                using (Transaction tx = localDb.TransactionManager.StartTransaction())
                //using (Database symbolerDB = new Database(false, true))
                {
                    try
                    {
                        System.Data.DataTable fjvKomponenter = IntersectUtilities.CsvReader.ReadCsvToDataTable(
                            @"X:\AutoCAD DRI - 01 Civil 3D\FJV Komponenter.csv", "FjvKomponenter");

                        //symbolerDB.ReadDwgFile(@"X:\0371-1158 - Gentofte Fase 4 - Dokumenter\01 Intern\" +
                        //                       @"02 Tegninger\01 Autocad\Autocad\01 Views\0.0 Fælles\Symboler.dwg",
                        //                       System.IO.FileShare.Read, true, "");

                        BlockTable bt = tx.GetObject(localDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                        foreach (oid Oid in bt)
                        {
                            BlockTableRecord btr = tx.GetObject(Oid, OpenMode.ForRead) as BlockTableRecord;

                            if (ReadStringParameterFromDataTable(btr.Name, fjvKomponenter, "Navn", 0) != null)// &&
                            //btr.Name == "DN32 90gr twin")
                            {
                                Extents3d bbox = new Extents3d();
                                bbox.AddBlockExtents(btr);

                                float width  = ts(Math.Abs(bbox.MaxPoint.X - bbox.MinPoint.X));
                                float height = ts(Math.Abs(bbox.MaxPoint.Y - bbox.MinPoint.Y));

                                //PP = None, NP = Vertical flip, PN = Horizontal flip, NN = Vertical and Horizontal flip
                                //NN is the same as rotating 180°
                                Flip[] flips = new Flip[4] {
                                    Flip.PP, Flip.PN, Flip.NN, Flip.NP
                                };
                                string[] flipNames = new string[] { "_PP", "_PN", "_NN", "_NP" };

                                for (int i = 0; i < flips.Length; i++)
                                {
                                    Svg.SvgDocument svg = new Svg.SvgDocument()
                                    {
                                        Width   = width,
                                        Height  = height,
                                        ViewBox = new Svg.SvgViewBox(ts(bbox.MinPoint.X),
                                                                     ts(-bbox.MaxPoint.Y),
                                                                     width, height)
                                    };

                                    var group = new Svg.SvgGroup();
                                    svg.Children.Add(group);
                                    //WCS ORIGO transform matrix
                                    double[] dMatrix = new double[16] {
                                        1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1
                                    };
                                    Matrix3d transform = new Matrix3d(dMatrix);
                                    DrawOrDiscardEntity(btr, tx, transform, group);//, upscale);
                                    AddTransforms(group, flips[i]);

                                    svg.Write(@"X:\AutoCAD DRI - 01 Civil 3D\Svg\"
                                              + btr.Name + flipNames[i] + ".svg");
                                }
                            }
                        }
                    }
                    catch (System.Exception ex)
                    {
                        tx.Abort();
                        ed.WriteMessage(ex.Message);
                        throw;
                    }

                    tx.Commit();
                };
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage(ex.Message);
            }
        }
示例#19
0
        private static SvgElement CreateElement <T>(XmlReader reader, bool fragmentIsDocument, SvgDocument document) where T : SvgDocument, new()
        {
            SvgElement createdElement = null;
            string     elementName    = reader.LocalName;
            string     elementNS      = reader.NamespaceURI;

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

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

                if (createdElement != null)
                {
                    SetAttributes(createdElement, reader, document);
                }
            }
            else
            {
                // All non svg element (html, ...)
                createdElement = new NonSvgElement(elementName);
                SetAttributes(createdElement, reader, document);
            }

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

            return(createdElement);
        }
示例#20
0
        internal static void SetPropertyValue(SvgElement element, string attributeName, string attributeValue, SvgDocument document)
        {
            var elementType = element.GetType();

            PropertyDescriptorCollection properties;

            lock (syncLock)
            {
                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(elementType, 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
                {
                    if (attributeName == "opacity" && attributeValue == "undefined")
                    {
                        attributeValue = "1";
                    }

                    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));
                }
            }
            else
            {
                //check for namespace declaration in svg element
                if (string.Equals(element.ElementName, "svg", StringComparison.OrdinalIgnoreCase))
                {
                    if (string.Equals(attributeName, "xmlns", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(attributeName, "xlink", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(attributeName, "xmlns:xlink", StringComparison.OrdinalIgnoreCase) ||
                        string.Equals(attributeName, "version", StringComparison.OrdinalIgnoreCase))
                    {
                        //nothing to do
                    }
                    else
                    {
                        //attribute is not a svg attribute, store it in custom attributes
                        element.CustomAttributes[attributeName] = attributeValue;
                    }
                }
                else
                {
                    //attribute is not a svg attribute, store it in custom attributes
                    element.CustomAttributes[attributeName] = attributeValue;
                }
            }
        }
示例#21
0
        private SvgElement CreateElement <T>(XmlReader reader, bool fragmentIsDocument, SvgDocument document) where T : SvgDocument, new()
        {
            SvgElement createdElement = null;
            string     elementName    = reader.LocalName;
            string     elementNS      = reader.NamespaceURI;

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

            if (elementNS == SvgAttributeAttribute.SvgNamespace || string.IsNullOrEmpty(elementNS))
            {
                if (elementName == "svg")
                {
                    createdElement = (fragmentIsDocument) ? new T() : new SvgFragment();
                }
                else
                {
                    ElementInfo validType = null;
                    if (AvailableElements.TryGetValue(elementName, out validType))
                    {
                        createdElement = (SvgElement)Activator.CreateInstance(validType.ElementType);
                    }
                    else
                    {
                        createdElement = new SvgUnknownElement(elementName);
                    }
                }

                if (createdElement != null)
                {
                    SetAttributes(createdElement, reader, document);
                }
            }
            else
            {
                // All non svg element (html, ...)
                createdElement = new NonSvgElement(elementName);
                SetAttributes(createdElement, reader, document);
            }

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

            return(createdElement);
        }
        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
            {
                var servers = new List <SvgPaintServer>();

                while (!string.IsNullOrEmpty(value))
                {
                    if (value.StartsWith("url(#"))
                    {
                        var leftParen = value.IndexOf(')', 5);
                        Uri id        = new Uri(value.Substring(5, leftParen - 5), UriKind.Relative);
                        value = value.Substring(leftParen + 1).Trim();
                        servers.Add((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
                    {
                        switch (CountHexDigits(value, 1))
                        {
                        case 3:
                            servers.Add(new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Substring(0, 4))));
                            value = value.Substring(4).Trim();
                            break;

                        case 6:
                            servers.Add(new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Substring(0, 7))));
                            value = value.Substring(7).Trim();
                            break;

                        default:
                            return(new SvgDeferredPaintServer(document, value));
                        }
                    }
                    else
                    {
                        return(new SvgColourServer((Color)_colourConverter.ConvertFrom(value.Trim())));
                    }
                }

                if (servers.Count > 1)
                {
                    return(new SvgFallbackPaintServer(servers[0], servers.Skip(1)));
                }
                return(servers[0]);
            }
        }
示例#23
0
    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();

                tSvg = SvgRemoveHidden(tSvg);
                tSvg = SvgLine(tSvg);

                string tFileName = Request.Form["filename"].ToString();
                if (tFileName == "")
                {
                    tFileName = "chart";
                }
                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  = Request.Form["width"].ToString();
                    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;
                        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.Flush();
                    Response.End();
                }
            }
        }
    }
示例#24
0
        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)
            {
                SetAttributes(createdElement, reader, document);
            }

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

            return(createdElement);
        }
示例#25
0
        /// <summary>
        /// Renders the heat map and saves the output to <c>filePath</c>. This is void alias to <see cref="Render"/>
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="filePath">The file path.</param>
        public Svg.SvgDocument RenderAndSave(HeatMapModel model, String filePath)
        {
            Svg.SvgDocument output = Render(model, filePath);

            return(output);
        }
示例#26
0
 public virtual void InitialiseFromXML(XmlTextReader reader, SvgDocument document)
 {
     throw new NotImplementedException();
 }
示例#27
0
        private void Form1_Load(object sender, EventArgs e)
        {
            this.FormBorderStyle = FormBorderStyle.None;        //Vollbildmodus
            this.WindowState     = FormWindowState.Maximized;   //Vollbildmodus

            SvgImage.Width  = 1200;                             // Größe des Svg-Bilds
            SvgImage.Height = 850;

            //Füge die Svg-Datei in die Picturebox(SvgImage) ein
            SVGParser.MaximumSize = new Size(SvgImage.Width, SvgImage.Height);
            selectedPath          = Application.StartupPath + @"/Europa.svg";
            svgDocument           = SVGParser.GetSvgDocument(selectedPath);
            SvgImage.Image        = SVGParser.GetBitmapFromSVG(selectedPath);



            int    i    = 0;
            string pfad = Application.StartupPath + @"/LänderPunkte.txt";
            // Textdatei öffnen, Umlaute richtig lesen
            StreamReader DateiLesen = new StreamReader(pfad, Encoding.Default);

            // Solange Dateiende nicht erreicht
            while (!DateiLesen.EndOfStream)
            {
                //eine Zeile aus der Textdatei lesen
                string   zeile = DateiLesen.ReadLine();
                string[] daten = zeile.Split(';');
                //Fülle das Array Länder
                Länder[i] = new Land();
                Länder[i].setNummer(Convert.ToInt32(daten[0]));
                Länder[i].setName(daten[1]);
                Länder[i].setpunkteLand(Convert.ToInt32(daten[2]));
                Länder[i].setHaupstadt(daten[3]);
                Länder[i].setpunkteHauptstadt(Convert.ToInt32(daten[4]));
                Länder[i].setpunkteBeides(Convert.ToInt32(daten[5]));
                i++;
            }
            // Datei schließen
            DateiLesen.Close();



            //Sprachsteuerung
            try
            {
                Recogn.SetInputToDefaultAudioDevice();
                Recogn.SpeechRecognized          += new EventHandler <SpeechRecognizedEventArgs>(recognizer_Speechrecognized);
                Recogn.SpeechRecognitionRejected += new EventHandler <SpeechRecognitionRejectedEventArgs>(recognizer_Speechnotrecognized);
            }
            catch
            {
                MessageBox.Show("Mikrofon fehlt!");
            }
            try
            {
                Grammar Grammatik = new Grammar(Application.StartupPath + @"/grammar.xml", "LänderuStädte");
                Recogn.UnloadAllGrammars();
                Recogn.LoadGrammar(Grammatik);

                Recogn.RecognizeAsync(RecognizeMode.Multiple);
            }
            catch
            {
                MessageBox.Show("fEHleeEeeEeR!11!");
            }
        }
        public ActionResult Export(FormCollection fc)
        {
            string tType     = fc["type"];
            string tSvg      = fc["svg"];
            string tFileName = fc["filename"];
            string tWidth    = fc["width"];

            if (string.IsNullOrEmpty(tFileName))
            {
                tFileName = "DefaultChart";
            }
            MemoryStream tData = new MemoryStream(Encoding.UTF8.GetBytes(tSvg));

            Svg.SvgDocument tSvgObj = SvgDocument.Open <SvgDocument>(tData);
            tSvgObj.Transforms = new SvgTransformCollection();
            float scalar = (float)int.Parse(tWidth) / (float)tSvgObj.Width;

            tSvgObj.Transforms.Add(new SvgScale(scalar, scalar));
            tSvgObj.Width  = new SvgUnit(tSvgObj.Width.Type, tSvgObj.Width * scalar);
            tSvgObj.Height = new SvgUnit(tSvgObj.Height.Type, tSvgObj.Height * scalar);
            MemoryStream tStream = new MemoryStream();
            string       tTmp    = new Random().Next().ToString();
            string       tExt    = "";

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

            case "image/jpeg":
                tExt = "jpg";
                break;

            case "application/pdf":
                tExt = "pdf";
                break;

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

            // Svg.SvgDocument tSvgObj = SvgDocument.Open<SvgDocument>(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;
                Document  tDocumentPdf = null;
                try
                {
                    tSvgObj.Draw().Save(tStream, ImageFormat.Png);
                    tDocumentPdf = new 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.Close();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    tDocumentPdf.Close();
                    tWriter.Close();
                    tData.Dispose();
                    tData.Close();
                }
                break;

            case "svg":
                tStream = tData;
                break;
            }
            tFileName = tFileName + "." + tExt;
            return(File(tStream.ToArray(), tType, tFileName));
        }
示例#29
0
        public void SaveImage(HttpContext context)
        {
            var aa = context.Request.Form["svg"];

            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);
                }
            }
        }
示例#30
0
        public object GetImage(string uriString)
        {
            string safeUriString;

            if (uriString.Length > 65519)
            {
                //Uri MaxLength is 65519 (https://msdn.microsoft.com/en-us/library/z6c2z492.aspx)
                safeUriString = uriString.Substring(0, 65519);
            }
            else
            {
                safeUriString = uriString;
            }

            try
            {
                var uri = new Uri(safeUriString, UriKind.RelativeOrAbsolute);

                // handle data/uri embedded images (http://en.wikipedia.org/wiki/Data_URI_scheme)
                if (uri.IsAbsoluteUri && uri.Scheme == "data")
                {
                    int dataIdx = uriString.IndexOf(",") + 1;
                    if (dataIdx <= 0 || dataIdx + 1 > uriString.Length)
                    {
                        throw new Exception("Invalid data URI");
                    }

                    // we're assuming base64, as ascii encoding would be *highly* unsusual for images
                    // also assuming it's png or jpeg mimetype
                    byte[] imageBytes = Convert.FromBase64String(uriString.Substring(dataIdx));
                    using (var stream = new MemoryStream(imageBytes))
                    {
                        return(Image.FromStream(stream));
                    }
                }

                if (!uri.IsAbsoluteUri)
                {
                    uri = new Uri(OwnerDocument.BaseUri, uri);
                }

                // should work with http: and file: protocol urls
                var httpRequest = WebRequest.Create(uri);

                using (WebResponse webResponse = httpRequest.GetResponse())
                {
                    using (var stream = webResponse.GetResponseStream())
                    {
                        if (stream.CanSeek)
                        {
                            stream.Position = 0;
                        }
                        if (uri.LocalPath.EndsWith(".svg", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var doc = SvgDocument.Open <SvgDocument>(stream);
                            doc.BaseUri = uri;
                            return(doc);
                        }
                        else
                        {
                            return(Bitmap.FromStream(stream));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error loading image: '{0}', error: {1} ", uriString, ex.Message);
                return(null);
            }
        }