Here i have explained how to Export Webpage with Images to pdf in Asp.Net C#.

Step 1) Add HTML:

<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#ff9933" Font-Bold="true" />
</asp:GridView>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>

Step 2) Import Namespaces

using System;
using System.Web;
using System.Web.UI;
using System.Data;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

Step 3) C#

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void BindGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));


// Creating Rows 
DataRow dtrow = dt.NewRow();   
dtrow["UserId"] = 1;            
dtrow["UserName"] = "Imran";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Allahbad";
dt.Rows.Add(dtrow);
       
dtrow = dt.NewRow();               
dtrow["UserId"] = 2;               
dtrow["UserName"] = "Shankar";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Delhi";
dt.Rows.Add(dtrow);
        
dtrow = dt.NewRow();             
dtrow["UserId"] = 3;              
dtrow["UserName"] = "Priya";
dtrow["Education"] = "CA";
dtrow["Location"] = "Shimla";
dt.Rows.Add(dtrow);

gvDetails.DataSource = dt;
gvDetails.DataBind();
}

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void btnPDF_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Users.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
this.Page.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0.0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}

Screenshot

Add Comments