In this article I will explain with an example, how to export Charts to PDF in ASP.Net MVC Razor.
This article will illustrate how to export Charts created from Database using Charts Helper class to PDF in ASP.Net MVC Razor.
 
 
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
Installing and adding reference of iTextSharp Library
In order to install and add reference of ITextSharp library, you will need to:-
1. Right Click the Project in Solution Explorer and click Manage NuGet Packages from the Context Menu.
Export Chart to PDF in ASP.Net MVC
 
2. Now you will need to look for iTextSharp package and once found, you need to click the Install Button.
Export Chart to PDF in ASP.Net MVC
 
 
Model
The following Model class consists of two properties i.e. ShipCity and TotalOrders.
public class OrderModel
{
    public string ShipCity { get; set; }
    public int TotalOrders { get; set; }
}
 
 
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateChart function is called which returns the Image of Chart in Byte Array format.
Inside the PopulateChart function, the statistical data for the Pie chart is fetched from the Orders table and it is populated into the Generic List of OrderModel class objects.
The Generic List of OrderModel class is passed to the Chart method which accepts the following parameters.
Width– width of the Chart.
Height – height of the Chart.
Theme (Optional) – Allows to set the Theme of the Chart from the predefined themes.
 
The following methods are also used.
AddTitle – Sets the Title for the Chart.
AddSeries – This method sets the type of Chart i.e. Pie, Bar, etc. and also sets the X and Y values for the Chart.
Finally, the Chart is converted into Byte Array format and returned which is later converted into BASE64 string and displayed in View using ViewBag object.
 
Action method for handling the PDF File Export and Download operation
This Action method is executed when the Export Submit button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
 
The Chart is again populated using the PopulateChart function and Image file is read in Byte Array format and added to the iTextSharp PDF document which will be saved in MemoryStream class object.
Finally the MemoryStream class object is converted to Byte Array and exported and downloaded as PDF file using the File function.
public ActionResult Index()
{
    byte[] bytes = PopulateChart();
    ViewBag.ChartImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
    return View();
}
 
[HttpPost]
public FileResult Export()
{
    byte[] bytes = PopulateChart();
    ViewBag.ChartImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length);
    using (MemoryStream stream = new System.IO.MemoryStream())
    {
        //Initialize the PDF document object.
        using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f))
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
            pdfDoc.Open();
 
            //Add the Image file to the PDF document object.
            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bytes);
            pdfDoc.Add(img);
            pdfDoc.Close();
 
            //Download the PDF file.
            return File(stream.ToArray(), "application/pdf", "Chart.pdf");
        }
    }
}
 
private static byte[] PopulateChart()
{
    string query = "SELECT TOP 5 ShipCity, COUNT(orderid) TotalOrders";
    query += " FROM Orders WHERE ShipCountry = 'USA' GROUP BY ShipCity";
    string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
    List<OrderModel> chartData = new List<OrderModel>();
 
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query))
        {
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    chartData.Add(new OrderModel
                    {
                        ShipCity = sdr["ShipCity"].ToString(),
                        TotalOrders = Convert.ToInt32(sdr["TotalOrders"])
                    });
                }
            }
 
            con.Close();
        }
    }
 
    Chart chart = new Chart(width: 500, height: 500, theme: ChartTheme.Blue);
    chart.AddTitle("USA City Distribution");
    chart.AddSeries("Default", chartType: "Pie", xValue: chartData, xField: "ShipCity", yValues: chartData, yFields: "TotalOrders");
    return chart.GetBytes(format: "jpeg");
}
 
 
View
Inside the View, the Chart is displayed using a HTML Image element whose SRC attribute is set to the ViewBag object.
There is also an HTML Submit button enclosed inside a Form with the Action method specified as Export.
When this Button will be clicked, first the Form is submitted and the Chart is exported and downloaded as PDF file.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <img alt="Chart" src="@ViewBag.ChartImageUrl" style="height:300px; width:300px"/>
    <br/>
    @using (Html.BeginForm("Export", "Home", FormMethod.Post))
    {
        <input type="submit" id="btnSubmit" value="Export"/>
    }
</body>
</html>
 
 
Screenshot
The Chart
Export Chart to PDF in ASP.Net MVC
 
The exported PDF file
Export Chart to PDF in ASP.Net MVC
 
 
Downloads