Saturday, 18 January 2014

Asp.net Export WebPage with Images to PDF using iTextSharp in C#, VB.NET

Here I will explain how to export webpage with images to PDF in asp.net using iTextSharp in c#, vb.net.
Description:

In my previous articles I explained clearly Export gridview data to excel or word, Export gridview data to CSV file, Export Gridview data to pdf in asp.net, upload data from excel to sql server database, Export selected rows of gridview to excel/word and many articles relating to gridview, asp.net, c#, vb.net. Now I will explain how to export webpage with images to PDF in asp.net using iTextSharp in c#vb.net.

In asp.net we don’t have a direct feature to export gridview data to PDF for that reason here I am using third party library ITextSharp reference. First download dll from this site ITextSharp after that create one new website in visual studio and add ITextsharp dll reference to newly created website after that write the following code in aspx page like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div><img src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgdIQKs25EZNsABpPgg3Hb2YKnHGb-vldkM_zp3sYH36y2hBlJ9yF1eNtmZUGcXtAahAAiHc0qm6kqZNfXv3A71LNsIc6nIUJKKrfcbcu4KTBfyFqBIknCI_ano4rLhiDIZo4VjK84f0I4/" /></div>
<div><b>Export Webpage with images to pdf using itextsharp dll</b></div><br />
<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="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnPDF" runat="server" Text="Export to PDF" OnClick="btnPDF_Click"/>
</form>
</body>
</html>
Now in code behind add these references


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;
After that write the following code in code behind

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));
DataRow dtrow = dt.NewRow();    // Create New Row
dtrow["UserId"] = 1;            //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();               // Create New Row
dtrow["UserId"] = 2;               //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow();              // Create New Row
dtrow["UserId"] = 3;              //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
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=UserDetails.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();
}
If you observe above code I added one function that is VerifyRenderingInServerFormthis function is used to avoid the error like “control must be placed in inside of form tag”. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly

VB.NET Code


Imports System.Web
Imports System.Web.UI
Imports System.Data
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
Dim dtrow As DataRow = dt.NewRow()
' Create New Row
dtrow("UserId") = 1
'Bind Data to Columns
dtrow("UserName") = "SureshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Chennai"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 2
'Bind Data to Columns
dtrow("UserName") = "MadhavSai"
dtrow("Education") = "MBA"
dtrow("Location") = "Nagpur"
dt.Rows.Add(dtrow)
dtrow = dt.NewRow()
' Create New Row
dtrow("UserId") = 3
'Bind Data to Columns
dtrow("UserName") = "MaheshDasari"
dtrow("Education") = "B.Tech"
dtrow("Location") = "Nuzividu"
dt.Rows.Add(dtrow)
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnPDF_Click(sender As Object, e As EventArgs)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Me.Page.RenderControl(hw)
Dim sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 100.0F, 0.0F)
Dim htmlparser As New HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub
End Class
Demo



Once we export data to pdf our output will be like this 


No comments:

Post a Comment