Export user details to PDF on ASP.Net GridView Print Button click using iTextSharp

Last Reply one year ago By pandeyism

Posted one year ago

Hi I had a gridview page which it contains the users id,fname,lname and five more things. Secondly i had create a view button in each row to redirect to another page called detail page, to view the details of the particluar user. Thirdly my requirement is i need one more button called print button so that the detail items to print as pdf with logo, footer, header to be inside the pdf page. I watch the link https://www.aspsnippets.com/Articles/Create-PDF-Report-from-database-in-ASPNet-using-C-and-VBNet.aspx

its covering my thoughts but not i exactly want, (I am new for the asp.net) and my code

protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            BindGridView();
        }
    }

    private void BindGridView()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("select * from move_details", con);
        DataTable dt = new DataTable();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EditButton")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            Response.Redirect("~/SD/EditView.aspx?EmpNo=" + row.Cells[0].Text);
        }
        if (e.CommandName == "PrintButton")
        {
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];
            
        }

    }

need help.

Thanks.

Posted one year ago Modified on one year ago

Hi sindiyen,

Check this example. Now please take its reference and correct your code.

If you want to more details about iTextSharp please refer below links

https://www.aspsnippets.com/Articles/Create-PDF-Report-from-database-in-ASPNet-using-C-and-VBNet.aspx

HTML

<asp:GridView ID="gvContact" runat="server" AutoGenerateColumns="false" AllowPaging="false"
    OnRowCommand="gvContact_RowCommand">
    <Columns>
        <asp:BoundField DataField="EmployeeId" HeaderText="EmployeeId" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:TemplateField HeaderText="Header1">
            <ItemTemplate>
                <asp:Button ID="btnedit" runat="server" Text="View" CommandName="View" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" />
                <asp:Button ID="Button1" runat="server" Text="Print" CommandName="Print" CommandArgument="<%#((GridViewRow) Container).RowIndex %>" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespaces

C#

using System.IO;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Configuration;
using System.Data.SqlClient;

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindEmployeesDropDown();
    }
}
private void BindEmployeesDropDown()
{
    gvContact.DataSource = GetData("SELECT EmployeeId, (FirstName + ' ' + LastName) Name FROM Employees");
    gvContact.DataBind();
}
private DataTable GetData(string query)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;

            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                return dt;
            }
        }
    }
}
protected void gvContact_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
    GridViewRow row = gvContact.Rows[index];
    if (e.CommandName == "View")
    {
        Response.Redirect("~/Details.aspx?EmployeeID=" + row.Cells[0].Text);
    }
    if (e.CommandName == "Print")
    {
        DataRow dr = GetData("SELECT EmployeeId, (FirstName + ' ' + LastName) Name FROM Employees where EmployeeID = " + row.Cells[0].Text).Rows[0];
        Document document = new Document(PageSize.A3, 88f, 88f, 10f, 10f);

        using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
            PdfPTable table = null;
            document.Open();
            table = new PdfPTable(3);
            table.AddCell(PhraseCell(new Phrase("Image")));
            table.AddCell(PhraseCell(new Phrase("Id")));
            table.AddCell(PhraseCell(new Phrase("Name")));
            table.AddCell(PhraseCell(new Phrase(" ")));
            table.AddCell(PhraseCell(new Phrase(" ")));
            table.AddCell(PhraseCell(new Phrase(" ")));
            table.AddCell(ImageCell("~/images/Chrysanthemum.jpg", 15f, PdfPCell.ALIGN_LEFT));
            table.AddCell(PhraseCell(new Phrase(dr["EmployeeId"].ToString())));
            table.AddCell(PhraseCell(new Phrase(dr["Name"].ToString())));
            document.Add(table);
            document.Close();
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment; filename=Employee.pdf");
            Response.Buffer = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
            Response.Close();
        }
    }
}
private static PdfPCell PhraseCell(Phrase phrase)
{
    PdfPCell cell = new PdfPCell(phrase);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.PaddingBottom = 2f;
    cell.PaddingTop = 0f;
    return cell;
}
private static PdfPCell ImageCell(string path, float scale, int align)
{
    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(path));
    image.ScalePercent(scale);
    PdfPCell cell = new PdfPCell(image);
    cell.BorderColor = Color.WHITE;
    cell.VerticalAlignment = PdfCell.ALIGN_TOP;
    cell.HorizontalAlignment = align;
    cell.PaddingBottom = 0f;
    cell.PaddingTop = 0f;
    return cell;
}

Screenshots