Click here to Skip to main content
15,884,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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

 
Share this answer
 
v3
Use This code
C#
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 :)
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900