How to Generate PDF Dynamically in Asp.Net

Description: We can Generate PDF through code in dot net using ItextSharp DLL. It’s very use full control to create many more thing in asp.net using this dll we can create pdf, xml etc. if we want to create pdf file from database also we have done before generate pdf file from database on button click or export data in pdf.

If we want to generate pdf dynamically then we can also done without button click or without using controls in dot net.

So let’s start how to achieve this functionality in dot for generating pdf file from database.

First Create Customer table in your Database

CREATE TABLE [dbo].[Customers](
      [ContactName] [varchar](20) NOT NULL,
      [City] [varchar](20) NOT NULL,
      [PostalCode] [int] NOT NULL,
      [Country] [varchar](20) NOT NULL,
      [Phone] [bigint] NOT NULL,
      [Fax] [bigint] NOT NULL,
      [CustomerId] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
      [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 1: Create Web page and Go to Code behind because of we don’t have to use any controls to generate PDF file directly we will generate PDF file from database on when page load first time in server.

Step 2: for getting data from database we have to create Connection String in code behind or in Web.Config file here we will create Connection String in Web.Config file because of it is very secure to use connection string in Web.Config file.

<connectionStrings>
       <add connectionString="Data Source= ServerName;Initial Catalog= DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" name="DBCS"/>
</connectionStrings>

Step 3: Create GetData () methods for getting data from database and return Data Table for Generating PDF file what we got data from database.
private void BindGrid()
{
    string strConnString = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GeneratePdf(dt);
                }
            }
        }
    }
}

Step 4: Now call this method in Page_load () method so when page load first time than it create automatically pdf file from that data.
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {        
        BindGrid();
    }
}

Step 5: Now Create GeneratePdf () Method for creation Pdf files from passed data table or else database data what we got in DataTable. Here we will create StringBuilder for Creating table in HtmlFile and Save data in Dynamically in Pdf file and read all data from DataTable row by row using looping. Using Document, HtmlWorker, PdfWriter through we will create pdf file and attachment through we will download directly from server if we want to save dynamically this file in server also we can done by using Server.MapPath and Giving by right path we can save this file in Server.

private void GeneratePdf(DataTable dt)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            string companyName = "AspCodder";
            int orderNo = 1000001;
            StringBuilder sb = new StringBuilder();
            sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
            sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Customer 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><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 />");
            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("</table>");
            StringReader sr = new StringReader(sb.ToString());

            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();

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

Step 6: run your webpage and see you will get proper output.

Related Posts

Previous
Next Post »

Thanks for comments.....