Popular Posts

Sunday, 29 September 2013

HOW TO CONVERT WEBPAGE INTO PDF FILE

HOW TO CONVERT WEBPAGE INTO PDF FILE

Here 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 http://sourceforge.net/projects/itextsharp/[^]
OR
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


THE CODE DESIGN :
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebpageToPdf.aspx.cs" Inherits="WebpageToPdf" EnableEventValidation="false"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form id="form1" runat="server">

<div><b>Export Webpage with images to pdf using itextsharp dll</b></div><br />
<div>
THIS IS THE TEST IMAGE ADDED FROM INTERNET:
 
  <div><img src="http://i328.photobucket.com/albums/l336/glamgalz/funzug/imgs/inspirational/cool_thoughts_persons_08.jpg" /></div>
 
  THIS IS THE TEST IMAGE ADDED FROM WEBAPPLICATION/PC FOLDER:
   <div>       <img src="images/thumbs/13.jpg" /></div>


</div>

<div>
SOME CONTENT IN WEB PAGE:
<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>YOU HAVE NOTICE THAT I HAVE KEPT EnableEventValidation="false" in bold due to following reason:
ERROR :
RegisterForEventValidation can only be called during Render();

This error occurs whenever we are trying to render control to response. To solve this problem I have added EnableEventValidation="false" to @Page directive of aspx page that should be just like this 

By Setting EnableEventValidation="false" property to @Page directive of aspx page the problem has solved automatically.




THE CODE BEHIND:



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;

public partial class WebpageToPdf : System.Web.UI.Page
{
    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"] = "PIYUSHRANA";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "NOIDA";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();               // Create New Row
        dtrow["UserId"] = 2;               //Bind Data to Columns
        dtrow["UserName"] = "PRAVEEN";
        dtrow["Education"] = "MBA";
        dtrow["Location"] = "MUMBAI";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "GANESH";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "MUMBAI";
        dt.Rows.Add(dtrow);

        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "MAHESH";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "CHENNAI";
        dt.Rows.Add(dtrow);
        dtrow = dt.NewRow();              // Create New Row
        dtrow["UserId"] = 3;              //Bind Data to Columns
        dtrow["UserName"] = "SANDEEP";
        dtrow["Education"] = "B.Tech";
        dtrow["Location"] = "MUMBAI";
        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);

        //if you want to add/insert images from your folder then add the below two lines
        string imageFilePath = Server.MapPath(".") + "/images/thumbs/13.jpg";
        iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(imageFilePath);
        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);
      
       png.ScaleToFit(110, 110);
        png.Alignment = iTextSharp.text.Image.UNDERLYING;
          png.SetAbsolutePosition(480, 800);

        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(png);
        htmlparser.Parse(sr);
        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
}


No comments :

Post a Comment