Showing posts with label iTextSharp PDF. Show all posts
Showing posts with label iTextSharp PDF. Show all posts

Tuesday, May 8, 2012

Generate PDF by Reading HTML File by Replacing Data.


Add itextsharp.dll
Create a Table called PersonalData with following column



Add Employment.htm file in project and create a HTML File

  <div id="divPersonalDataContainer">
    <table>
        <tr>
            <td bgcolor="#0066ff" colspan = "6" >
               <span style ="color:White">Personal Data</span>
            </td>
        </tr>
    </table>
        <div id="tablContainer">
            <table class="tableclass">
                <tr>
                    <td>
                        <b>Salutation</b>
                    </td>
                    <td class="LableValue">
                        {Salutation}
                    </td>
                    <td class="LableText">
                        <b>First Name</b>
                    </td>
                    <td class="LableValue">
                        {First Name}
                    </td>
                    <td class="LableText">
                        <b>Middle Name</b>
                    </td>
                    <td class="LableValue">
                        {Middle Name}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Last Name</b>
                    </td>
                    <td class="LableValue">
                        {Last Name}
                    </td>
                    <td class="LableText">
                        <b>Nick Name</b>
                    </td>
                    <td class="LableValue">
                        {Nick Name}
                    </td>
                    <td class="LableText">
                    </td>
                    <td class="LableValue">
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Present Address</b>
                    </td>
                    <td class="LableValue" colspan="5">
                        {Present Address}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>City</b>
                    </td>
                    <td class="LableValue">
                        {City}
                    </td>
                    <td class="LableText">
                        <b>State</b>
                    </td>
                    <td class="LableValue">
                        {State}
                    </td>
                    <td class="LableText">
                        <b>Country</b>
                    </td>
                    <td class="LableValue">
                        {Country}
                    </td>
                </tr>
                <tr>
                    <td class="LableText">
                        <b>Zip Code</b>
                    </td>
                    <td class="LableValue">
                        {Zip Code}
                    </td>
                    <td class="LableText">
                        <b>Home Phone</b>
                    </td>
                    <td class="LableValue">
                        {Home Phone}
                    </td>
                    <td class="LableText">
                        <b>Email</b>
                    </td>
                    <td class="LableValue">
                        {Email}
                    </td>
                </tr>
            
                <tr>
                    <td colspan="6">
                    </td>
                </tr>
            </table>
        </div>
   </div>


Create a TestForm.aspx and in code behind write

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;


public partial class TestForm : System.Web.UI.Page
{
  
    protected void Page_Load(object sender, EventArgs e)
    {
            //Just For Demo we have Retriving detail for EmployeId=1
            int Id = 1;
            SetControl(Id);
      

    }
    public void SetControl(int EmpID)
    {
        try
        {
            SqlConnection con = new SqlConnection(@"Your database connectionstring.");
            con.Open();
            string s = "select * from PersonalData where EmployeeID=" + EmpID + "";
            SqlCommand cmd = new SqlCommand(s, con);
            SqlDataReader dr = cmd.ExecuteReader();
            string fileContents;

            string FilePath = Server.MapPath("EmploymentForm.htm");
            StreamReader mstrFileStreamReader = new StreamReader(FilePath);
            try
            {
                fileContents = mstrFileStreamReader.ReadToEnd();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                mstrFileStreamReader.Close();
            }
            while (dr.Read())
            {
                if (dr != null)
                {
                    if (!String.IsNullOrEmpty(dr[0].ToString()))
                    {
                        fileContents = fileContents.Replace("{Salutation}", dr["Suffix"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Salutation}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["LastName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Last Name}", dr["LastName"].ToString());
                    }
                    else { fileContents = fileContents.Replace("{Last Name}", ""); }
                    if (!String.IsNullOrEmpty(dr["FirstName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{First Name}", dr["FirstName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{First Name}", "");

                    }
                    if (!String.IsNullOrEmpty(dr["MiddleName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Middle Name}", dr["MiddleName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Middle Name}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["NickName"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Nick Name}", dr["NickName"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Nick Name}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["PresentAddress"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Present Address}", dr["PresentAddress"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Present Address}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["City"].ToString()))
                    {
                        fileContents = fileContents.Replace("{City}", dr["City"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{City}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["State"].ToString()))
                    {
                        fileContents = fileContents.Replace("{State}", dr["State"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{State}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["Country"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Country}", dr["Country"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Country}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["ZipCode"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Zip Code}", dr["ZipCode"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Zip Code}", "");
                    }
                    if (!String.IsNullOrEmpty(dr["HomePhone"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Home Phone}", dr["HomePhone"].ToString());
                    }
                    else { fileContents = fileContents.Replace("{Home Phone}", ""); }

                    if (!String.IsNullOrEmpty(dr["EmailAddress"].ToString()))
                    {
                        fileContents = fileContents.Replace("{Email}", dr["EmailAddress"].ToString());
                    }
                    else
                    {
                        fileContents = fileContents.Replace("{Email}", "");
                    }

                }
                else
                {
                    fileContents = fileContents.Replace("{Salutation}", "");
                    fileContents = fileContents.Replace("{Last Name}", "");
                    fileContents = fileContents.Replace("{First Name}", "");
                    fileContents = fileContents.Replace("{Middle Name}", "");
                    fileContents = fileContents.Replace("{Nick Name}", "");
                    fileContents = fileContents.Replace("{Present Address}", "");
                    fileContents = fileContents.Replace("{City}", "");
                    fileContents = fileContents.Replace("{State}", "");
                    fileContents = fileContents.Replace("{Country}", "");
                    fileContents = fileContents.Replace("{Zip Code}", "");
                    fileContents = fileContents.Replace("{Home Phone}", "");

                    fileContents = fileContents.Replace("{Email}", "");

                }
            
              
                byte[] result = createPDF(fileContents.ToString()).GetBuffer();

                Response.Clear();
                Response.AddHeader("Content-Length", result.Length.ToString());
                Response.ContentType = "application/pdf";
                Response.AddHeader("Accept-Ranges", "bytes");
                Response.Buffer = true;
                Response.AddHeader("Expires", "0");
                Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
                Response.AddHeader("Pragma", "public");
                Response.AddHeader("content-Transfer-Encoding", "binary");
                string filename = dr["FirstName"].ToString()+"-"+dr["LastName"].ToString();//set Name Of PDF file
              
                Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                Response.BinaryWrite(result);
                Response.Flush();
                Response.End();


              

            }
            dr.Close();
            con.Close();
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
  
    }
    private MemoryStream createPDF(string html)
    {
        MemoryStream msOutput = new MemoryStream();
        TextReader reader = new StringReader(html);
        // step 1: creation of a document-object    
        Document document = new Document(PageSize.A4, 0, 0, 50, 50);
      
        // step 2:        // we create a writer that listens to the document
        // and directs a XML-stream to a file  
        PdfWriter writer = PdfWriter.GetInstance(document, msOutput);

       iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();

       styles.LoadStyle("headerdiv", "height", "30px");
       styles.LoadStyle("headerdiv", "font-weight", "bold");
       styles.LoadStyle("headerdiv", "font-size", "20px");
       styles.LoadStyle("headerdiv", "background-color", "Blue");
       styles.LoadStyle("headerdiv", "color", "Blue");
       styles.LoadStyle("headerdiv", "padding-left", "5px");
       styles.LoadStyle("tableclass", "font-family", "Calibri");
       //styles.LoadStyle("tableclass", "font-size", "5px");
       styles.LoadStyle("LableText", "font-weight", "bold");
       //styles.LoadStyle("LableValue", "font-weight", "normal");
       styles.LoadTagStyle("td", "padding", "0 5px 0 5px");
    


       HTMLWorker worker = new HTMLWorker(document);
       worker.SetStyleSheet(styles);


       // step 4: we open document and start the worker on the document
       document.Open();
       worker.StartDocument();
       // step 5: parse the html into the document    
       worker.Parse(reader);
       // step 6: close the document and the worker  
       worker.EndDocument();
       worker.Close();
       document.Close();

        return msOutput;
    }

}

Download sample from here......
Download

Thursday, September 1, 2011

Generate pdf of gridview in asp.net


I will Explain You how to create PDF from Gridview.
Try to create a gridview that display in left

Then Click Event of both button

protected void btnGeneratePDF_Click(object sender, EventArgs e)
{
int columnCount = GridView1.Columns.Count;
int rowCount = GridView1.Rows.Count;

Document Doc = new Document();


PdfPTable grdTable = new PdfPTable(columnCount);

grdTable.AddCell("FirstName");
grdTable.AddCell("LastName");
for (int rowCounter = 0; rowCounter < rowCount; rowCounter++)
{
for (int columnCounter = 0; columnCounter < columnCount; columnCounter++)
{
string strValue = GridView1.Rows[rowCounter].Cells[columnCounter].Text;
grdTable.AddCell(strValue);
}
}

PdfWriter.GetInstance(Doc, new FileStream(Request.PhysicalApplicationPath + "/pdf/Name.pdf", FileMode.Create));
Doc.Open();
Doc.Add(new Paragraph("Student Information"));
Doc.Add(new Paragraph("\n"));
Doc.Add(grdTable);
Doc.Close();
grdTable.SpacingBefore = 15f;

}
protected void PDF_Click(object sender, EventArgs e)
{
PdfPTable table = new PdfPTable(gvdetails.Columns.Count);
int[] widths = new int[gvdetails.Columns.Count];

for (int x = 0; x < gvdetails.Columns.Count; x++)
{
// widths[x] = (int)gvdetails.Columns[x].ItemStyle.Width.Value;
string cellText = Server.HtmlEncode(gvdetails.Columns[x].HeaderText);

PdfPCell cell = new PdfPCell(new Phrase(cellText));

cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#EFF3FB"));
table.AddCell(cell);
}
// table.SetWidths(widths);
for (int i = 0; i < gvdetails.Rows.Count; i++)
{
if (gvdetails.Rows[i].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvdetails.Columns.Count; j++)
{
string cellText = gvdetails.Rows[i].Cells[j].Text;
PdfPCell cell = new PdfPCell(new Phrase(cellText));
if (i % 2 != 0)
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#D1DDF1"));
}
table.AddCell(cell);
}
}
}
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

PdfWriter.GetInstance(pdfDoc, new FileStream(Request.PhysicalApplicationPath + "/pdf/data.pdf", FileMode.Create));
pdfDoc.Open();
pdfDoc.Add(new Paragraph("Student Information"));
pdfDoc.Add(new Paragraph("\n\n"));
pdfDoc.Add(table);

pdfDoc.Close();
table.SpacingBefore = 15f;
Response.End();

}

Both button have the same functionality but the different in second button is that I created the colorful gridview in PDF