Export GridView as Image to Excel PDF using C# and VB.Net in ASP.Net

Last Reply one month ago By pandeyism

Posted one month ago

I am trying to export multiple GridViews from a web form into either Excel or PDF using VB.net. I need to maintain all GridView formatting so that the export looks as it does on the web form. I also need the GridViews to export into a single page, not a page per GridView. I have had success exporting the data from the GridViews into Excel and PDF, but it is just the data and all formatting is non existent. I thought that if I exported these as images, then they would maintain their formatting and look the same in the export as they do in the Web Form.

I just keep coming up short in trying to convert them to images. Any assistance would be greatly appreciated.

You are viewing reply posted by: pandeyism one month ago.
Posted one month ago Modified on one month ago

Hi iamjer76,

Refer below sample.

HTML

<asp:Panel runat="server" ID="pnlImage">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
            <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
            <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
        </Columns>
    </asp:GridView>
    <br />
    <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
            <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
            <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
        </Columns>
    </asp:GridView>
</asp:Panel>
<asp:HiddenField ID="hfImageData" runat="server" />
<br />
<asp:Button ID="btnExport" Text="Export To   Pdf" runat="server" UseSubmitBehavior="false"
    OnClick="ExportToPdf" OnClientClick="return ConvertToImage(this)" />
<br />
<asp:Button Text="Export To Excel" runat="server" runat="server" OnClick="ExportToExcel"
    UseSubmitBehavior="false" OnClientClick="return ConvertToImage(this)" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script type="text/javascript">
    function ConvertToImage(btnExport) {
        html2canvas($("[id*=pnlImage]")[0], {
            onrendered: function (canvas) {
                var base64 = canvas.toDataURL();
                $("[id*=hfImageData]").val(base64);
                __doPostBack(btnExport.name, "");
            }
        });
        return false;
    }
</script>

Namespaces

C#

using System.Data;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.IO;

VB.Net

Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Name", typeof(string)),
                        new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
        GridView2.DataSource = dt;
        GridView2.DataBind();
    }
}

protected void ExportToPdf(object sender, EventArgs e)
{
    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
    byte[] bytes = Convert.FromBase64String(base64);
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bytes);
    pdfDoc.Add(img);
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=GridView.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    Response.End();
}

protected void ExportToExcel(object sender, EventArgs e)
{
    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
    byte[] bytes = Convert.FromBase64String(base64);
    string filepath = string.Format("~/Files/GridView.jpg");
    File.WriteAllBytes(Server.MapPath(filepath), bytes);
    System.Web.UI.WebControls.Image imgCapture = new System.Web.UI.WebControls.Image();
    imgCapture.ImageUrl = this.GetAbsoluteUrl(filepath);
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            System.Web.UI.WebControls.Table table = new System.Web.UI.WebControls.Table();
            TableRow row = new TableRow();
            row.Cells.Add(new TableCell());
            row.Cells[0].Controls.Add(imgCapture);
            table.Rows.Add(row);
            table.RenderControl(hw);
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=Images.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }
}

private string GetAbsoluteUrl(string relativeUrl)
{
    relativeUrl = relativeUrl.Replace("~/", string.Empty);
    string[] splits = Request.Url.AbsoluteUri.Split('/');
    if (splits.Length >= 2)
    {
        string url = splits[0] + "//";
        for (int i = 2; i < splits.Length - 1; i++)
        {
            url += splits[i];
            url += "/";
        }

        return url + relativeUrl;
    }
    return relativeUrl;
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As DataTable = New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
        dt.Rows.Add(1, "John Hammond", "United States")
        dt.Rows.Add(2, "Mudassar Khan", "India")
        dt.Rows.Add(3, "Suzanne Mathews", "France")
        dt.Rows.Add(4, "Robert Schidner", "Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
        GridView2.DataSource = dt
        GridView2.DataBind()
    End If
End Sub

Protected Sub ExportToPdf(ByVal sender As Object, ByVal e As EventArgs)
    Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","c)(1)
    Dim bytes As Byte() = Convert.FromBase64String(base64)
    Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 10.0F)
    Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(bytes)
    pdfDoc.Add(img)
    pdfDoc.Close()
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=GridView.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.Write(pdfDoc)
    Response.[End]()
End Sub

Protected Sub ExportToExcel(ByVal sender As Object, ByVal e As EventArgs)
    Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(","c)(1)
    Dim bytes As Byte() = Convert.FromBase64String(base64)
    Dim filepath As String = String.Format("~/Files/GridView.jpg")
    File.WriteAllBytes(Server.MapPath(filepath), bytes)
    Dim imgCapture As System.Web.UI.WebControls.Image = New System.Web.UI.WebControls.Image()
    imgCapture.ImageUrl = Me.GetAbsoluteUrl(filepath)
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
            Dim table As System.Web.UI.WebControls.Table = New System.Web.UI.WebControls.Table()
            Dim row As TableRow = New TableRow()
            row.Cells.Add(New TableCell())
            row.Cells(0).Controls.Add(imgCapture)
            table.Rows.Add(row)
            table.RenderControl(hw)
            Response.Clear()
            Response.Buffer = True
            Response.AddHeader("content-disposition", "attachment;filename=Images.xls")
            Response.Charset = ""
            Response.ContentType = "application/vnd.ms-excel"
            Response.Write(sw.ToString())
            Response.Flush()
            Response.[End]()
        End Using
    End Using
End Sub

Private Function GetAbsoluteUrl(ByVal relativeUrl As String) As String
    relativeUrl = relativeUrl.Replace("~/", String.Empty)
    Dim splits As String() = Request.Url.AbsoluteUri.Split("/"c)
    If splits.Length >= 2 Then
        Dim url As String = splits(0) & "//"
        For i As Integer = 2 To splits.Length - 1 - 1
            url += splits(i)
            url += "/"
        Next
        Return url & relativeUrl
    End If
    Return relativeUrl
End Function