1

I need to save a chart made in a WPF UserControl in a vector graphics file format.

What I have tried until now was to get a hold of the UIElement (the User Control) containing the chart, and save that as a .wmf file. I know that WPF renders the UserControls in a vector graphics format, so it seems that saving this file should be really straightforward. Anyway, it seems that I can get a hold of the user control, but can't see what is inside, I have tried to place it in a canvas but that doesn't seem to work. I tried to use a canvas because I already managed to save a .wmf file from the Child Shapes in a Canvas.

    private void InterceptChart()
    {
        TChartCanvas.Children.Add(new VisualHost { Visual=chart1});

    }
    public class VisualHost : UIElement
    {
        public Visual Visual { get; set; }
        protected override int VisualChildrenCount
        {
            get { return Visual != null ? 1 : 0; }
        }
        protected override Visual GetVisualChild(int index)
        {
            return Visual;
        }
    }
   public void Export(string filePath, Canvas MyCanvas)
    {

        int w = Convert.ToInt32(this.MyCanvas.Width);
        int h = Convert.ToInt32(this.MyCanvas.Height);
        System.Drawing.RectangleF rect = new System.Drawing.RectangleF(0, 0, w, h);
        Bitmap bmp = new Bitmap(16, 16);
        Graphics gs = Graphics.FromImage(bmp);
        Metafile mf = new Metafile(filePath, gs.GetHdc(), rect, MetafileFrameUnit.Pixel);
        Graphics g = Graphics.FromImage(mf);
        WPFPainter painter = new WPFPainter(g, MyCanvas);
        painter.Draw(); //painter takes the child shapes from the canvas and draws them using System.Drawing.Graphics
        g.Save();
        g.Dispose();
        mf.Dispose();
    }

I really hope there is a way to do this, because using a bitmap format to save these charts would make them useless, and I can't afford to re-write all the classes related to the graphics, but maybe I'm approaching this in the wrong way, if so I would appreciate if you could point me in the right direction. Cheers!

  • I think you would either need to write your own SVG exporter. Or search for some sort of 3rd party library. As far as i know, there is not .NET solution for this. – Ginger Ninja May 30 '19 at 15:25

0 Answers0