Tuesday, October 11, 2011

Export SQl Data into PDF with image

Add Reference the ItextSharp.dll file for creating PDF File


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

public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    SqlConnection cn = new SqlConnection("Data Source=Servername;Initial Catalog=Databasename;Integrated security=True");
    protected void Page_Load(object sender, EventArgs e)
    {
       
        cn.Open();
        SqlCommand cd = new SqlCommand("select * from table_name", cn);
 
        SqlDataAdapter da = new SqlDataAdapter(cd);
        da.Fill(dt);
        //ExportDaataSetTopdf(ds."report");


        Document  document = new Document(PageSize.A4, 50, 50, 150, 50);

        // Create a new PdfWrite object, writing the output to the file ~/PDFTemplate/Report.pdf
        FileStream  output = new FileStream(Server.MapPath("~/PDFTemplate/Report.pdf"), FileMode.Create);
        PdfWriter  writer = PdfWriter.GetInstance(document, output);

        // Open the Document for writing
        document.Open();
        iTextSharp.text.Image  logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/logo.jpg"));
        logo.SetAbsolutePosition(350, 730);
        document.Add(logo);
        if (dt != null)
        {

            PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
            PdfPCell PdfPCell = null;

            for (int rows = 0; rows < dt.Rows.Count; rows++)
            {
                if (rows == 0)
                {
                    for (int column = 0; column < dt.Columns.Count; column++)
                    {
                        PdfPCell = new PdfPCell(new Phrase(dt.Columns[column].ColumnName.ToString()));
                        PdfTable.AddCell(PdfPCell);
                    }
                }
                for (int column = 0; column < dt.Columns.Count; column++)
                {
                    PdfPCell = new PdfPCell(new Phrase(dt.Rows[rows][column].ToString()));
                    PdfTable.AddCell(PdfPCell);
                }
            }

            // Finally Add pdf table to the PDF document
            document.Add(PdfTable);
        }
        document.Close();
        cn.Close();
    }
}

No comments: