65.9K
CodeProject is changing. Read more.
Home

How to capture image and print the MSChart

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.05/5 (11 votes)

Sep 2, 2004

1 min read

viewsIcon

101277

downloadIcon

3515

How to capture image and print the MSChart.

Introduction

MSChart is a control that comes with .NET framework and it can be used for applications written in C# or VB.NET. Below is the description of MSChart which I took from MSDN.

The MSChart control supports the following features:

  • True three-dimensional representation.
  • Support for all major chart types.
  • Data grid population via random data and data arrays.

And this one comes from me...

MSChart control is free of charge! :)

I would like to share some of my experiences dealing with MSChart.

  1. How to capture the image?
  2. How to Print Preview and Print the Chart?

Hope this will be useful to the public. Here it goes...

Reminder

A reminder to include these two important classes!

using System.Drawing.Printing;
using System.Drawing.Imaging;

Instructions

  1. Create a normal Windows Form in C#.
  2. Create a MSChart on the Form.
  3. Create a toolbar with three buttons - with names (e.g.: toolBarbtnCapture, toolBarbtnPrintPreview, toolBarbtnPrint).
  4. Create an ImageList.
  5. Load three images into the ImageList.
  6. Link the ImageList with the toolbar through the ToolBarButton property: ImageList.
  7. In the 'ToolBarButton Collection Editor', specify the ImageIndex.

Copy and paste the code below and it will work! Voila! :)

private void printGraph_PrintPage(object sender, 
       System.Drawing.Printing.PrintPageEventArgs e)
{
  MSChart.EditCopy();
  Bitmap chartCapture = 
      (Bitmap) Clipboard.GetDataObject().GetData("Bitmap", true);
  //setting the alignment for the printing session

  e.Graphics.DrawImage(chartCapture, 8,80);
  chartCapture.Dispose();
}

private void toolBar_ButtonClick(object sender, 
     System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
  switch (e.Button.ImageIndex)
  {
    case 0:
      MSChart.EditCopy();
      Bitmap chartCapture = 
        (Bitmap) Clipboard.GetDataObject().GetData("Bitmap", true);
      chartCapture.Save("Image.Jpeg");
      break;
    case 1:
      try
      {
        //setting the print layout to landscape

        printGraph.DefaultPageSettings.Landscape = true;
        printPreviewDialog.Document = this.printGraph;
        printPreviewDialog.ShowDialog();
      }
      catch(Exception exp)
      {
        MessageBox.Show(exp.ToString());
      }
      break;
    case 2:
      printGraph.DefaultPageSettings.Landscape = true;
      printDialog.Document = printGraph;
      if(printDialog.ShowDialog() == DialogResult.OK)
      {
        printGraph.Print();
      }
      break;
  }
}

The code will detect the image index (not the toolbar button index) pressed. Might be a lame way to do it but please bear with the beginner! :)