Pdf can be downloaded in two ways in asp.net they are:
*) Using Script.
*) Using third party pdf creation dll files (iTextSharp).
1) Lets us first see pdf download using scripting
Step 1: Write the following script in ur .aspx page.
<script type="text/javascript">
function PrintGridData() {
var prtGrid = document.getElementById('<%=GridView1.ClientID %>');
prtGrid.border = 0;
var prtwin = window.open('', 'PrintGridViewData', 'left=100,top=100,width=1000,height=1000,tollbar=0,scrollbars=1,status=0,resizable=1');
prtwin.document.write(prtGrid.outerHTML);
prtwin.document.close();
prtwin.focus();
prtwin.print();
prtwin.close();
}
</script>
Step 2: Now add a simple button to call the above function.
<input type="button" id="btnPrint" value="Convert To PDF" önclick="PrintGridData()" />
2) Now Lets download pdf using Third party dll
Step 1: Download the iTextSharp dll from the following website
[
iTextSharp pdf dll Download]
Step 2: Extract the dll and add it to your project by following these simple steps
right click on references (Solution Explorer)
-> add reference
-> navigate to where the dll is extracted
-> Select the dll and click ok.
Step 3: Now add a button to your aspx page as follows:
<asp:button id="pdf" runat="server" text="Convert to PDF" onclick="pdf_Click" xmlns:asp="#unknown" />
Step 4: Now in c# code add the following namespaces
using System;
using System.IO;
using System.Web;
using System.Web.UI;
using iTextSharp.text;
using iTextSharp.text.pdf;
using MySql.Data.MySqlClient;
using System.Web.UI.WebControls;
using iTextSharp.text.html.simpleparser;
step 5: Now write the code for button click(pdf_Click) as follows
protected void pdf_Click(object sender, EventArgs e)
{
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", "PDF.pdf"));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter writer = new StringWriter();
HtmlTextWriter textwriter = new HtmlTextWriter(writer);
this.Page.RenderControl(textwriter);
StringReader reader = new StringReader(writer.ToString());
Document pdfdoc = new Document(PageSize.A4, 20f, 20f, 20f, 20f);
HTMLWorker worker = new HTMLWorker(pdfdoc);
PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
pdfdoc.Open();
worker.Parse(reader);
pdfdoc.Close();
Response.Write(pdfdoc);
Response.End();
}
Happy coding.