title: Trying to Export Data Grid View to PDF using C#
body: <p><a href="https://i.stack.imgur.com/6cxLX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6cxLX.png" alt="enter image description here"></a></p>
  
  <p>Trying to Export the Data Grid View to a PDF file using C#</p>
  
  <p>The <strong>btnexport_Click</strong> event calls the Method ExportGridToPDF();</p>
  
  <p>Here is the code below:</p>
  
  <pre><code>   private void btnexport_Click(object sender, EventArgs e)
  
      {          
        ExportGridToPDF();  
      }
  
  
     private void ExportGridToPDF()
  
      {
          Response.ContentType = "application/pdf";
          Response.AddHeader("content-disposition", "attachment;filename=GetStudent.pdf");
          Response.Cache.SetCacheability(HttpCacheability.NoCache);
          StringWriter sw = new StringWriter();
          HtmlTextWriter hw = new HtmlTextWriter(sw);
          dataGridView1.RenderControl(hw);
          StringReader sr = new StringReader(sw.ToString());
          Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
          HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
          PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
          pdfDoc.Open();
          htmlparser.Parse(sr);
          pdfDoc.Close();
          Response.Write(pdfDoc);
          Response.End();
          dataGridView1.AllowPaging = false;
          dataGridView1.DataBind();           
      } 
  </code></pre>