This is a migrated thread and some comments may be shown as answers.

Export Chart

5 Answers 346 Views
ChartView
This is a migrated thread and some comments may be shown as answers.
ali
Top achievements
Rank 1
ali asked on 13 Jan 2020, 06:23 AM

I want Export a chart in pdf file and image file. I use MVVM. I define a cartesian chart in view model and export that. but is some problem in export.

My chart is like "Ui.png" and in xaml that work correct.

* But in pdf file ("Export.pdf"):

1- label of Axis overwrite on corner.

2- some of curve have dasharray (you can see in "Ui.png") but dosen't set.

3- I define a Plot band Annotation (you can see in "Ui.png") but dosen't set.

* And in png file ("Export.png") only show Axis label.

My code for export

--------------------------------------------------------------------------------------------------------

RadFixedDocument document = new RadFixedDocument();
Chart = CreateChart();
document.Pages.Add(CreateChartPdfPart());

PdfFormatProvider provider = new PdfFormatProvider();
provider.Export(document, fileStream);

--------------------------------------------------------------------------------------------------------

public RadCartesianChart CreateChart()
        {
            RadCartesianChart Chart = new RadCartesianChart();
            DoubleCollection dashArray = new DoubleCollection { 10, 1, 1, 1 };
            FontFamily fontFamily = new FontFamily(Properties.Settings.Default.FontFamily);
            Chart.BeginInit();

            DateTimeContinuousAxis AxisX = new DateTimeContinuousAxis();
            AxisX.PlotMode = AxisPlotMode.OnTicks;
            AxisX.LabelFitMode = AxisLabelFitMode.Rotate;
            AxisX.ShowLabels = true;
            Chart.HorizontalAxis = AxisX;

            LinearAxis LengthAxis = new LinearAxis();
            LengthAxis.HorizontalLocation = AxisHorizontalLocation.Right;
            LengthAxis.LineDashArray = dashArray;
            TextBlock txt = new TextBlock();
            var RotateLabel = new Style(typeof(TextBlock));
            Setter setter = new Setter(TextBlock.RenderTransformProperty, new RotateTransform() { Angle = 180, CenterX = 50, CenterY = 50 });
            RotateLabel.Setters.Add(setter);
            txt.Style = RotateLabel;
            txt.Text = string.Format(CultureInfo.CreateSpecificCulture("en-US"), "Difference (cm)");
            LengthAxis.Title = txt.Text;

            var ColorLabel = new Style(typeof(TextBlock));
            Setter sett = new Setter(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.Black));
            LengthAxis.LabelStyle = ColorLabel;
            LengthAxis.ShowLabels = true;

            LinearAxis PercentageAxis = new LinearAxis();
            PercentageAxis.HorizontalLocation = AxisHorizontalLocation.Left;
            PercentageAxis.Title = string.Format(CultureInfo.CreateSpecificCulture("en-US"), ""); //"Difference (%)"
            PercentageAxis.ShowLabels = true;
            Chart.VerticalAxis = PercentageAxis;

            Chart.Width = sizeA4.Width - 40;
            Chart.Height = (sizeA4.Width - 40) * (2.0 / 3.0);

            CartesianPlotBandAnnotation BandAnnotation = new CartesianPlotBandAnnotation();
            BandAnnotation.Axis = PercentageAxis;
            BandAnnotation.From = DownWarn;
            BandAnnotation.To = UpWarn;
            BandAnnotation.BorderBrush = new SolidColorBrush(Colors.Green);
            BandAnnotation.Fill = new SolidColorBrush(Colors.Green);
            Chart.Annotations.Add(BandAnnotation);

            CartesianGridLineAnnotation GridLineAnnotationMinFail = new CartesianGridLineAnnotation();
            GridLineAnnotationMinFail.Axis = PercentageAxis;
            GridLineAnnotationMinFail.Value = DownFailure;
            GridLineAnnotationMinFail.Stroke = new SolidColorBrush(Colors.Red);
            GridLineAnnotationMinFail.DashArray = new DoubleCollection { 5, 5 };
            GridLineAnnotationMinFail.StrokeThickness = 0.5;
            Chart.Annotations.Add(GridLineAnnotationMinFail);

            CartesianGridLineAnnotation GridLineAnnotationMaxFail = new CartesianGridLineAnnotation();
            GridLineAnnotationMaxFail.Axis = PercentageAxis;
            GridLineAnnotationMaxFail.Value = UpFailure;
            GridLineAnnotationMaxFail.Stroke = new SolidColorBrush(Colors.Red);
            GridLineAnnotationMaxFail.DashArray = new DoubleCollection { 5, 5 };
            GridLineAnnotationMaxFail.StrokeThickness = 0.5;
            Chart.Annotations.Add(GridLineAnnotationMaxFail);

            CartesianChartGrid ChartGrid = new CartesianChartGrid();
            ChartGrid.MajorLinesVisibility = GridLineVisibility.X;
            ChartGrid.StripLinesVisibility = GridLineVisibility.Y;
            ChartGrid.IsTabStop = false;
            ChartGrid.YStripeBrushes.Add(new SolidColorBrush(Colors.Gray));
            Chart.Grid = ChartGrid;

            int i = 0;
            foreach (var data in Data)
            {
                LineSeries lineSeries;
                if (chekboxSeries[i])
                {
                    if (i == 0 || i == 1 || i == 2 || i == 7 || i == 8)
                    {
                        lineSeries = new LineSeries
                        {
                            Stroke = new SolidColorBrush(newColor[i]),
                            StrokeThickness = 0.5,
                            DashArray = dashArray
                        };
                    }
                    else
                    {
                        lineSeries = new LineSeries
                        {
                            Stroke = new SolidColorBrush(newColor[i]),
                            VerticalAxis = LengthAxis,
                            DashArray = dashArray,
                            StrokeThickness = 0.5
                        };
                    }
                    foreach (var item in data.Items)
                    {
                        lineSeries.DataPoints.Add(new CategoricalDataPoint { Category = item.Date, Value = item.Value });
                    }
                    Chart.Series.Add(lineSeries);
                }
                i++;
            }
            Chart.EndInit();
            Chart.Measure(new Size(Chart.Width, Chart.Height));
            Chart.Arrange(new Rect(new Point(0, 0), Chart.DesiredSize));
            return Chart;
        }

--------------------------------------------------------------------------------------------------------

private RadFixedPage CreateChartPdfPart()
        {
            int margin = 20;
            var page = new RadFixedPage();
            page.Size = sizeA4;
            var editor = new FixedContentEditor(page, Telerik.Windows.Documents.Fixed.Model.Data.MatrixPosition.Default);

            using (editor.SavePosition())
            {
                editor.Position.Translate(margin, margin);
                ExportUIElement.ExportHelper.ExportToPdf(Chart, editor);
            }
            return page;
        }

--------------------------------------------------------------------------------------------------------

private void ExportPNGToImage(FrameworkElement element, Stream stream)
        {
            Telerik.Windows.Media.Imaging.ExportExtensions.ExportToImage(element, stream, new PngBitmapEncoder());
        }

 

What is wrong?

 

5 Answers, 1 is accepted

Sort by
0
Martin Ivanov
Telerik team
answered on 16 Jan 2020, 07:34 AM

Hello Ali,

The following KB article shows how to save the chart to an image without adding it in the visual tree.

https://docs.telerik.com/devtools/wpf/knowledge-base/kb-chartview-export-to-image-in-code

I hope that helps.

Regards,
Martin Ivanov
Progress Telerik

Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Minita
Top achievements
Rank 1
Veteran
answered on 16 Sep 2020, 05:58 AM

Hi Martin,

I am using RadListBox, and each item contains one RadCartesianChartView. Also I am setting minimum height to each item as 200. Whenever there are more than 3 or 4 items in RadListBox, Vertical Scrollbar will appear. 

Everything works perfect till here. Now, I want to export these charts. When I use telerik provided export in image functionality, it exports only the visible area of RadListBox.

Is it possible to export all(e.g. 10) charts present in RadListBox in an image?

Thanks & Regards,
Minita

0
Dilyan Traykov
Telerik team
answered on 18 Sep 2020, 02:32 PM

Hi Minita,

Here's an example of how you can export all the RadCartesianChart instances in a RadListBox control using the approach demonstrated in the KB article Martin provided:

        private static int counter = 0;
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            foreach (RadListBoxItem item in this.ListBox.Items)
            {
                var chart = item.Content as RadCartesianChart;

                var measureSize = new Size(500, 500);
                item.Measure(measureSize);
                item.Arrange(new Rect(measureSize));
                item.UpdateLayout();

                chart.Width = chart.RenderSize.Width;
                chart.Height = chart.RenderSize.Height;
                chart.OnApplyTemplate();
                chart.UpdateLayout(); 
                
                string filename = "ExportedChart" + ++counter + ".png";
                using (Stream fileStream = File.Open(filename, FileMode.OpenOrCreate))
                {
                    Telerik.Windows.Media.Imaging.ExportExtensions.ExportToImage(chart, fileStream, new PngBitmapEncoder());
                }
            }
        }
Please give this a try and let me know if it works for you.

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
Minita
Top achievements
Rank 1
Veteran
answered on 18 Sep 2020, 04:09 PM

Hello Dilyan,

Thank you for the response. I am looking for something which can export all the charts into single image, not multiple images.

If we use RadListBox's instance in ExportToImage() method, I can get what I am looking for. But it exports only visible area of the listbox. I have attached images for reference.

Thanks & Regards,

Minita

0
Dilyan Traykov
Telerik team
answered on 22 Sep 2020, 10:52 AM

Hello Minita,

In such case you can use an approach similar to the one described in this thread to combine the images into a single one.

As for the difference in the size of the expected and actual image, you can make the following modification to the code snippet I provided:

var measureSize = new System.Windows.Size(this.ListBox.ActualWidth, this.ListBox.ActualHeight);
This will measure the charts with the width of their parent RadListBox. I hope you can now manage to achieve the desired result.

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
ChartView
Asked by
ali
Top achievements
Rank 1
Answers by
Martin Ivanov
Telerik team
Minita
Top achievements
Rank 1
Veteran
Dilyan Traykov
Telerik team
Share this question
or