Generate Invoice (Bill) Receipt using C# and VB.Net in ASP.Net

Last Reply one month ago By arunkurmi

Posted one month ago

Dear Friends/Sir,

I am using ASP.NET, C# and SQL

In my project everything is working fine viewing Values from Database in Gridview, Add, Update Delete, Convert DatagridView Values to Excel and pdf.

But now i want to Print Datagridview values with Company Details like company name, Contact Details, Address etc as header like in Bills/Invoices. 


Posted one month ago

Dear Dharmendr Sir,

Thank you very much for your suggestion,

it is an Excellent guide by Mr. Mudassar Ahmed Khan

In all Examples Data used is Dummy Data(as Said by the Mr. Mudassar Ahmed Khan Article)

but in my Project Data will be in <asp:GridView> as shown below data is fetched from DataBase using C#

 

                        <asp:GridView ID="EmployeeGridViewList"  CssClass="table table-bordered" runat="server">
                            <Columns>
                                <asp:TemplateField HeaderText="Sl. No.">
                                    <ItemTemplate>
                                        <asp:Label ID="lblRowNumber" Text='<%# Container.DataItemIndex + 1 %>' runat="server" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:CommandField ShowSelectButton="true" />
                            </Columns>
                        </asp:GridView>

i am using below code to convert PDF and it is working fine

    protected void btnExportToPDF_Click(object sender, EventArgs e)
    {
        using (StringWriter sw = new StringWriter())
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            EmployeeGridViewList.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10, 0f);
            PdfWriter wrt = PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
            pdfdoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(wrt, pdfdoc, sr);
            pdfdoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Category.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfdoc);
            Response.End();
        }
    }

Mr. Mudassar Khan is using below code to covert to pdf with data from the html page itself 

protected void GenerateInvoicePDF(object sender, EventArgs e)
{
    //Dummy data for Invoice (Bill).
    string companyName = "ASPSnippets";
    int orderNo = 2303;
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[5] {
                            new DataColumn("ProductId", typeof(string)),
                            new DataColumn("Product", typeof(string)),
                            new DataColumn("Price", typeof(int)),
                            new DataColumn("Quantity", typeof(int)),
                            new DataColumn("Total", typeof(int))});
    dt.Rows.Add(101, "Sun Glasses", 200, 5, 1000);
    dt.Rows.Add(102, "Jeans", 400, 2, 800);
    dt.Rows.Add(103, "Trousers", 300, 3, 900);
    dt.Rows.Add(104, "Shirts", 550, 2, 1100);
 
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            StringBuilder sb = new StringBuilder();
 
            //Generate Invoice (Bill) Header.
            sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
            sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Order Sheet</b></td></tr>");
            sb.Append("<tr><td colspan = '2'></td></tr>");
            sb.Append("<tr><td><b>Order No: </b>");
            sb.Append(orderNo);
            sb.Append("</td><td align = 'right'><b>Date: </b>");
            sb.Append(DateTime.Now);
            sb.Append(" </td></tr>");
            sb.Append("<tr><td colspan = '2'><b>Company Name: </b>");
            sb.Append(companyName);
            sb.Append("</td></tr>");
            sb.Append("</table>");
            sb.Append("<br />");
 
            //Generate Invoice (Bill) Items Grid.
            sb.Append("<table border = '1'>");
            sb.Append("<tr>");
            foreach (DataColumn column in dt.Columns)
            {
                sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
                sb.Append(column.ColumnName);
                sb.Append("</th>");
            }
            sb.Append("</tr>");
            foreach (DataRow row in dt.Rows)
            {
                sb.Append("<tr>");
                foreach (DataColumn column in dt.Columns)
                {
                    sb.Append("<td>");
                    sb.Append(row[column]);
                    sb.Append("</td>");
                }
                sb.Append("</tr>");
            }
            sb.Append("<tr><td align = 'right' colspan = '");
            sb.Append(dt.Columns.Count - 1);
            sb.Append("'>Total</td>");
            sb.Append("<td>");
            sb.Append(dt.Compute("sum(Total)", ""));
            sb.Append("</td>");
            sb.Append("</tr></table>");
 
            //Export HTML String as PDF.
            StringReader sr = new StringReader(sb.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Invoice_" + orderNo + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }

i tried the above code as it is, it worked good but i tried to add heading to my asp:gridview but failed, is there any way to concatinate the header with that asp:gridview which is converted to PDF,

hope you understood

please help


Posted one month ago Modified on one month ago

Hi mdkh,

Check this sample. now take its reference.

You can design your own table structure for print as you need.

HTML

<div id="dvPrint" runat="server">
    <table>
        <tr>
            <td colspan="2"><center><b><u>Order Details</u></b></center></td>
        </tr>
        <tr>
            <td>Company Name : <u><b>AspSnippets.com</b></u></td>
            <td>Date : <u><asp:Label ID="lblDate" Text="" runat="server" /></u></td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false">
                    <Columns>
                        <asp:BoundField DataField="OrderID" HeaderText="Order ID" />
                        <asp:BoundField DataField="OrderDate" HeaderText="Order Date" DataFormatString="{0:dd/mm/yyyy}" />
                        <asp:BoundField DataField="CustomerID" HeaderText="Customer Name" />
                        <asp:BoundField DataField="Freight" HeaderText="Price" DataFormatString="{0:N2}" />
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>
    <asp:Button ID="btnPrint" Text="Print" runat="server" OnClick="OnPrint" />
</div>

Namespaces

C#

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;

VB.Net

Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        lblDate.Text = DateTime.Now.ToString();
        this.BindOrders();
    }
}


public override void VerifyRenderingInServerForm(Control control)
{
    /*Verifies that the control is rendered */
}

protected void OnPrint(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        dvPrint.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10, 0f);
        PdfWriter wrt = PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
        pdfdoc.Open();
        XMLWorkerHelper.GetInstance().ParseXHtml(wrt, pdfdoc, sr);
        pdfdoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=OrderDetails.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfdoc);
        Response.End();
    }
}

private void BindOrders()
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 5 OrderID,OrderDate,CustomerID,Freight FROM Orders", con))
        {
            cmd.CommandType = CommandType.Text;
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                sda.SelectCommand = cmd;
                DataTable dt = new DataTable();
                sda.Fill(dt);
                this.gvOrders.DataSource = dt;
                this.gvOrders.DataBind();
            }
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        lblDate.Text = DateTime.Now.ToString()
        Me.BindOrders()
    End If
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub

Protected Sub OnPrint(ByVal sender As Object, ByVal e As EventArgs)
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
            dvPrint.RenderControl(hw)
            Dim sr As StringReader = New StringReader(sw.ToString())
            Dim pdfdoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10, 0.0F)
            Dim wrt As PdfWriter = PdfWriter.GetInstance(pdfdoc, Response.OutputStream)
            pdfdoc.Open()
            XMLWorkerHelper.GetInstance().ParseXHtml(wrt, pdfdoc, sr)
            pdfdoc.Close()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=OrderDetails.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.Write(pdfdoc)
            Response.[End]()
        End Using
    End Using
End Sub

Private Sub BindOrders()
    Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
        Using cmd As SqlCommand = New SqlCommand("SELECT TOP 5 OrderID,OrderDate,CustomerID,Freight FROM Orders", con)
            cmd.CommandType = CommandType.Text
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                sda.SelectCommand = cmd
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                Me.gvOrders.DataSource = dt
                Me.gvOrders.DataBind()
            End Using
        End Using
    End Using
End Sub

Screenshot