Click here to Skip to main content
14,385,236 members
Rate this:
Please Sign up or sign in to vote.
See more:
How to Create create the pdf in asp .net c# to all formating i have try using iTextsharp dll but having error "Object reference not set to an instance of an object."on code line
"gvdetails.HeaderRow.Style.Add("width", "15%");".
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

   
v3
Rate this:
Please Sign up or sign in to vote.

Solution 2

Use This code
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Then write the code as:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindEmpGrid();
        }
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //It solves the error "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."
    }
    protected void BindEmpGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from EMPLOYEE", con);
        DataTable dt = new DataTable();
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(dt);
        grEmp.DataSource = dt;
        grEmp.DataBind();
    }

  protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ClearContent();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=MyPdfFile.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter strWrite = new StringWriter();
            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);
            HtmlForm frm = new HtmlForm();
            grEmp.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(grEmp);
            frm.RenderControl(htmWrite);
            StringReader sr = new StringReader(strWrite.ToString());
            Document pdfDoc = new Document(PageSize.A4, 8f, 8f, 8f, 2f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.Flush();
            Response.End();
        }
        catch (Exception ex) { }
    }


Thanks & Regard
Sham :)
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100