Bind and Export GridView data to PDF file in asp.net(C#, VB.Net)

Introduction: In previous articles i explained How to bind and Export GridView data to Ms Word file and How to bind and Export GridView data to Ms Excel file  and Bind and Export GridView data to CSV file in asp.net and Bind,Save,Edit,Update,Cancel,Delete,Paging example in GridView and Search in gridview and How to Bind,save,edit,update,delete records from DataList and How to pass parameter to stored procedure using SqlDataAdapter and check login in asp.net  and  How to read DataKeyName from GridView on SelectedindexChanging event of GridView .
In this article I am going to explain how easily you can bind GridView with sql server database data and Export that Gridview data to PDF (Portable Document Format) file using asp.net with C# and VB.Net.  First we will learn how to bind data from sql server table to Gridview data control and then how to export that Gridview data to PDF file. 
Bind and Export GridView data to PDF File in asp.net
Click on image to enlarge
Implementation: Let’s understand by creating an asp.net web application
    Bind and Export GridView data to PDF in asp.net
    Click on image to enlarge
  • Create a Database e.g. "MyDataBase" and a table under that DataBase in Sql Server and name it "EMPLOYEE" as shown in figure: 


Note: EMP_ID column is set to Primary key and Identity specification is set to yes with Identity increment and Identity seed equal to 1. Insert some data in this table that you  want to show in the Gridview.


  • Now in web.config file add the connectionstring under <configuration> tag
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LocalServer;Initial Catalog=MyDataBase;Integrated Security=True"/>
  </connectionStrings>

Note: Replace the Data Source and Initial Catalog as per your application.
  • In the design page (.aspx) drag and place a GridView data control from visual studio toolbox to bind data and also place a Button control to Export the GridView data to PDF file.
Source Code:

<fieldset style="width:360px;">
            <legend>Bind and Export GridView data to PDF in asp.net</legend>
            <table>
                <tr>
                    <td>
                        <asp:GridView ID="grEmp" runat="server" AllowPaging="True" AutoGenerateColumns="False"
                   GridLines="None" Width="100%" CellPadding="4" ForeColor="#333333">
                   
                    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />                   
                    <Columns>
                        <asp:BoundField DataField="EMP_NAME" HeaderText="Emp Name"  />
                        <asp:BoundField DataField="DEPT" HeaderText="Department"  />
                        <asp:BoundField DataField="SALARY" HeaderText="salary"  />
                        <asp:BoundField DataField="EMAIL_ID" HeaderText="Email Id" />
                    </Columns>                  
                    <EditRowStyle BackColor="#999999" />
                    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                    <SortedAscendingCellStyle BackColor="#E9E7E2" />
                    <SortedAscendingHeaderStyle BackColor="#506C8C" />
                    <SortedDescendingCellStyle BackColor="#FFFDF8" />
                    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                </asp:GridView>
                    </td>               
                </tr>
                <tr>
                    <td>
<asp:Button ID="btnExportToPdf" runat="server" Text="Export To PDF File" OnClick="btnExportToPdf_Click" />
                    </td>
                </tr>
            </table>
        </fieldset>
  • To export gridview data to pdf file you need to add the reference of itextsharp.dll in to you website. Below are the steps to download and add itextsharp.dll to your application.
Step 1: open the link itextpdf.com/download.php in the browser

Step 2: You will find a link "Download iTextSharp", the C# port of the library

Step 3: On clicking the link you will find the link to download the latest version. The current version i found right now is  is itextsharp-all-5.4.2.zip (5.0 MB)

Step 4: Extract the downloaded zipped folder itextsharp-all-5.4.2.zip.There are also some other zipped folders inside.You just extract the folder itextsharp-dll-core and you will find the required itextsharp.dll.

Step: 5: Copy the itextsharp.dll file and paste in the Bin folder of your root directory. If there is no Bin folder in the root directory then right clcik on your website name in the solution explorer -> Add -> Add ASP.NET Folder -> Bin. Now paste copied itextsharp.dll file in the Bin folder

C#.Net Code to Bind and Export GridView data to PDF file

First include the following namespaces

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Then write the code as:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindEmpGrid();
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    }
    protected void BindEmpGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from EMPLOYEE", con);
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        grEmp.DataSource = dt;
        grEmp.DataBind();
    }

  protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ClearContent();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=MyPdfFile.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter strWrite = new StringWriter();
            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
            HtmlForm frm = new HtmlForm();
            grEmp.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(grEmp);
            frm.RenderControl(htmWrite);
            StringReader sr = new StringReader(strWrite.ToString());
            Document pdfDoc = new Document(PageSize.A4, 8f, 8f, 8f, 2f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex) { }
    }

VB.Net Code to Bind and Export GridView data to PDF file

First include the following namespaces

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Net
Imports System.Net.Mail
Imports System.Web.UI.HtmlControls
Imports System.IO
Imports System.Text
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser

Then write the code as:

  Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindEmpGrid()
        End If
    End Sub

    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        'It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    End Sub

    Protected Sub BindEmpGrid()
        Dim cmd As New SqlCommand("select * from EMPLOYEE", con)
        Dim dt As New DataTable()
        Dim adp As New SqlDataAdapter(cmd)
        adp.Fill(dt)
        grEmp.DataSource = dt
        grEmp.DataBind()
    End Sub

Protected Sub btnExportToPdf_Click(sender As Object, e As EventArgs)
        Try
            Response.ClearContent()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=MyPdfFile.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Dim strWrite As New StringWriter()
            Dim htmWrite As New HtmlTextWriter(strWrite)
            Dim frm As New HtmlForm()
            grEmp.Parent.Controls.Add(frm)
            frm.Attributes("runat") = "server"
            frm.Controls.Add(grEmp)
            frm.RenderControl(htmWrite)
            Dim sr As New StringReader(strWrite.ToString())
            Dim pdfDoc As New Document(PageSize.A4, 8.0F, 8.0F, 8.0F, 2.0F)
            Dim htmlparser As New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            htmlparser.Parse(sr)
            pdfDoc.Close()
            Response.Write(pdfDoc)
            Response.Flush()
            Response.[End]()
        Catch ex As Exception
        End Try
    End Sub

Notice that I have added an overriding function VerifyRenderingInServerForm in the code behind. This is to resolve the error “Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server” that may occur while exporting GridView data to MS Excel file or MS Word file or PDF(Portable Document Format) or CSV (Comma separated value) file. 

Note: To view complete article on why this error occur and how to resolve that error, read my article “How to Solve Error Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server
  • After exporting gridview data to PDF file, will look as shown in figure:

Bind and Export GridView data to PDF File in asp.net
Click on image to enlarge

Now over to you:

"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates."
Previous
Next Post »

21 comments

Click here for comments
saurabh
admin
September 05, 2013 ×

very nice post thanks

Reply
avatar
September 05, 2013 ×

Thanks for the appreciation saurabh. stay tuned and stay connected

Reply
avatar
Unknown
admin
September 17, 2013 ×

Lalit I really glade to say this your work is superb and most Appreciated,thank you very much May Allah Almighty Give you the best of best....

Reply
avatar
September 17, 2013 ×

Thank you Norulla khan..this is one of the best comment for my blog..may god bless you too..keep reading :)

Reply
avatar
Unknown
admin
September 17, 2013 ×

Lalit I am trying this but here is pretty error that shows me that
"System.Web.HttpException: A page can have only one server-side Form tag."
I have a datewise reports system in ma project when I select date from calendar into textbox & a button which has a text "Search Record" once the button clicked then data will shown on Gridview
then I've one more button i.e "ExportToPdf".
when I clicked then the above error is Occurred.so please kindly help me Bro.it's Urgent ..awaiting for your reply.
Once again Thank you so much ....

Reply
avatar
September 18, 2013 ×

I think your page consists of 2 form tags.Remove the unnecessary one.More than one form marked with "run at server" on your ASP page is not allowed..try and notify if the error not solved..

Reply
avatar
Unknown
admin
September 18, 2013 ×

Lalit I've figured out the Problem and the Problem is
I'm using Asp.net with Master page but In our Coding We're using
"Dim frm1 As New HtmlForm()","Dim htmlparser As New HTMLWorker(pdfDoc)"..........!!!!!!and so On ..
but that's the reason I'm facing the Above mentioned error messages which I've posted in ma last comment.
So Am Probing every where but I am failed ...So kindly if your reply would be appreciated ....thank you for giving your precious time

Reply
avatar
Danish Khan
admin
September 19, 2013 ×

sir if i want to send Email this pdf file as an attachment so what i do.

Reply
avatar
Anonymous
admin
September 20, 2013 ×

This is really what I was searching for!!.. Thanks a lot..

Reply
avatar
September 20, 2013 ×

i am glad my article helped you..keep reading :)

Reply
avatar
Unknown
admin
September 23, 2013 ×

Lalit I am Sorry to disturb you again ,I've been trying to work since 6 days On Exports Pdf but am Unable to do.As I mentioned in ma last comment please help me out . If we are Implementing the above code in asp.net page then it will take two form Tag.because in coding itself we are creating One more form i.e .Dim frm1 As New HtmlForm()..Please do help me..I would be greatfull to you.

Reply
avatar
September 23, 2013 ×

Hello Noorulla Khan..send me your project example on my email id lalit24rocks@gmail.com and i will check and try to solve your issue as soon as possible on getting time..

Reply
avatar
Unknown
admin
September 25, 2013 ×

sir,one problem create with me,that is document doesn't contain constructor that contains 5 argument,then in htmlworker best over loaded method and the pdfwriter,plz sir tel me how i wil solve this error.
Thanks advancely.
krupalini

Reply
avatar
Unknown
admin
September 25, 2013 ×

hello sir i wiil solve that error,sorry 4 disturbing u.

Reply
avatar
September 25, 2013 ×

I am glad you will solve your problem yourself..i like your spirit...keep reading.:)

Reply
avatar
Unknown
admin
October 21, 2013 ×

Hello lalit, I'm varsha. The data which are binded in gridview during runtime will be converted into pdf format. if i work separately i ll work fine. but if i ll' put in my project, that button event not work properly. give me some solution for this issue. as soon as possible

Reply
avatar
Unknown
admin
October 21, 2013 ×

Hi Lalit, the issue is converting gridview data into pdf, separately works fine. but if i ll' put the same coding in my project its not working. please help me.

Reply
avatar
October 22, 2013 ×

Hello Shanthini Varsha..What is the exact error you are facing in your project..Let me know and i will help you in resolving that error...

Reply
avatar
June 06, 2014 ×

Your welcome Shaaban Alqassas..

Reply
avatar
Anonymous
admin
August 20, 2014 ×

Hello Lalit,

Hope you are doing good.

I saw your blog and it is very interesting. Thank you for such people like you who share their abilities. Anyway, I was working with gridview that should be exported to pdf. I was able to export the data from gridview, but the item that I have to solve is to put the column header for each of the page generated in pdf. Column header was only available in 1st page of pdf. I hope you can help me with this one. Thank you in advance. :)

Regards
Vincent

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..