Blank PDF generated while exporting ASP.Net Chart to PDF using iTextSharp

Last Reply 3 months ago By pandeyism

Posted 3 months ago

I copy paste the code from the example on the site,it runs, but the downloaded pdf is blank. It contains only the legend.

How can I resolve this issue?

Export ASP.Net Chart Control to PDF Document using iTextSharp Library

Posted 3 months ago

Hi ada20,

Refer below links -

HTML

<asp:DropDownList ID="ddlCountries" runat="server" OnSelectedIndexChanged="ddlCountries_SelectedIndexChanged"
    AutoPostBack="true">
</asp:DropDownList>
<hr />
<asp:Chart ID="Chart1" runat="server" Height="300px" Width="400px">
    <Titles>
        <asp:Title ShadowOffset="3" Name="Items" />
    </Titles>
    <Legends>
        <asp:Legend Alignment="Center" Docking="Bottom" IsTextAutoFit="False" Name="Default"
            LegendStyle="Row" />
    </Legends>
    <Series>
        <asp:Series Name="Default" />
    </Series>
    <ChartAreas>
        <asp:ChartArea Name="ChartArea1" BorderWidth="0" />
    </ChartAreas>
</asp:Chart>
<br />
<asp:Button ID="btnExportPDF" runat="server" Text="Export to PDF" OnClick="btnExportPDF_Click" />

Namespaces

C#

using System.Configuration;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Web.UI.DataVisualization.Charting;
using System.Data;
using System.Data.SqlClient;

VB.Net

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.Web.UI.DataVisualization.Charting
Imports System.Data
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "select distinct shipcountry from orders";
        DataTable dt = GetData(query);
        ddlCountries.DataSource = dt;
        ddlCountries.DataTextField = "shipcountry";
        ddlCountries.DataValueField = "shipcountry";
        ddlCountries.DataBind();
        ddlCountries.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Select", ""));
    }
}

protected void ddlCountries_SelectedIndexChanged(object sender, EventArgs e)
{
    CreatChart();
}

private void CreatChart()
{
    Chart1.Visible = ddlCountries.SelectedValue != "";
    string query = string.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", ddlCountries.SelectedValue);
    DataTable dt = GetData(query);
    string[] x = new string[dt.Rows.Count];
    int[] y = new int[dt.Rows.Count];
    for (int i = 0; i < dt.Rows.Count; i++)
    {
        x[i] = dt.Rows[i][0].ToString();
        y[i] = Convert.ToInt32(dt.Rows[i][1]);
    }
    Chart1.Series[0].Points.DataBindXY(x, y);
    Chart1.Series[0].ChartType = SeriesChartType.Pie;
    Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;
    Chart1.Legends[0].Enabled = true;
}

private static DataTable GetData(string query)
{
    DataTable dt = new DataTable();
    SqlCommand cmd = new SqlCommand(query);
    String constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter();
    cmd.CommandType = CommandType.Text;
    cmd.Connection = con;
    sda.SelectCommand = cmd;
    sda.Fill(dt);
    return dt;
}

protected void btnExportPDF_Click(object sender, EventArgs e)
{
    CreatChart();
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    using (MemoryStream stream = new MemoryStream())
    {
        Chart1.SaveImage(stream, ChartImageFormat.Png);
        iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
        chartImage.ScalePercent(75f);
        pdfDoc.Add(chartImage);
        pdfDoc.Close();

        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Chart.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim query As String = "select distinct shipcountry from orders"
        Dim dt As DataTable = GetData(query)
        ddlCountries.DataSource = dt
        ddlCountries.DataTextField = "shipcountry"
        ddlCountries.DataValueField = "shipcountry"
        ddlCountries.DataBind()
        ddlCountries.Items.Insert(0, New System.Web.UI.WebControls.ListItem("Select", ""))
    End If
End Sub

Protected Sub ddlCountries_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    CreatChart()
End Sub

Private Sub CreatChart()
    Chart1.Visible = ddlCountries.SelectedValue <> ""
    Dim query As String = String.Format("select shipcity, count(orderid) from orders where shipcountry = '{0}' group by shipcity", ddlCountries.SelectedValue)
    Dim dt As DataTable = GetData(query)
    Dim x As String() = New String(dt.Rows.Count - 1) {}
    Dim y As Integer() = New Integer(dt.Rows.Count - 1) {}

    For i As Integer = 0 To dt.Rows.Count - 1
        x(i) = dt.Rows(i)(0).ToString()
        y(i) = Convert.ToInt32(dt.Rows(i)(1))
    Next

    Chart1.Series(0).Points.DataBindXY(x, y)
    Chart1.Series(0).ChartType = SeriesChartType.Pie
    Chart1.ChartAreas("ChartArea1").Area3DStyle.Enable3D = True
    Chart1.Legends(0).Enabled = True
End Sub

Private Shared Function GetData(ByVal query As String) As DataTable
    Dim dt As DataTable = New DataTable()
    Dim cmd As SqlCommand = New SqlCommand(query)
    Dim constr As String = ConfigurationManager.ConnectionStrings("ConString").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim sda As SqlDataAdapter = New SqlDataAdapter()
    cmd.CommandType = CommandType.Text
    cmd.Connection = con
    sda.SelectCommand = cmd
    sda.Fill(dt)
    Return dt
End Function

Protected Sub btnExportPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
    CreatChart()
    Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()

    Using stream As MemoryStream = New MemoryStream()
        Chart1.SaveImage(stream, ChartImageFormat.Png)
        Dim chartImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(stream.GetBuffer())
        chartImage.ScalePercent(75.0F)
        pdfDoc.Add(chartImage)
        pdfDoc.Close()
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=Chart.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Response.Write(pdfDoc)
        Response.[End]()
    End Using
End Sub

Screenshot