Sunday, June 3, 2012

html to pdf using itextSharp

In previous article we checked how to convert gridview to pdf.

https://blogabhijeet.blogspot.com/2012/06/gridview-to-pdf-using-itextsharp.html

First of all you need to convert contents of html to Pdf. There is an third party dll:- iTextSharp dll which will help us to convert html contents to pdf.

Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/

Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.

Currently we have taken form and we are showing contents of current page in pdf.

Design Page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShowCurrentContentPageinPdf.aspx.cs" Inherits="Default2" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:PlaceHolder ID="PlaceholderPdf" runat="server"></asp:PlaceHolder>
    <div>
        <table border="1">
            <tr>
                <td colspan="2">
                    aspdotnetcodebook
                </td>
            </tr>
            <tr>
                <td>
                    cell1
                </td>
                <td>
                    cell2
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblLabel" runat="server" Text="Label Test"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    <p>
        &nbsp;</p>
    <p>
        xzcv</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        sdvasd</p>
    <p>
        &nbsp;</p>
    <p>
        &nbsp;</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </p>
    </form>
</body>
</html>
Code Behind Page 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text.RegularExpressions;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml;
using System.Xml;
using iTextSharp.text.html.simpleparser;
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


    }

    protected override void Render(HtmlTextWriter writer)
    {
        MemoryStream mem = new MemoryStream();
        StreamWriter twr = new StreamWriter(mem);
        HtmlTextWriter myWriter = new HtmlTextWriter(twr);
        base.Render(myWriter);
        myWriter.Flush();
        myWriter.Dispose();
        StreamReader strmRdr = new StreamReader(mem);
        strmRdr.BaseStream.Position = 0;
        string pageContent = strmRdr.ReadToEnd();
        strmRdr.Dispose();
        mem.Dispose();
        writer.Write(pageContent);
        CreatePDFDocument(pageContent);


    }
    public void CreatePDFDocument(string strHtml)
    {

        string strFileName = HttpContext.Current.Server.MapPath("test.pdf");
        // step 1: creation of a document-object
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        PdfWriter.GetInstance(document, new FileStream(strFileName, FileMode.Create));
        StringReader se = new StringReader(strHtml);
        HTMLWorker obj = new HTMLWorker(document);
        document.Open();
        obj.Parse(se);
        document.Close();
        ShowPdf(strFileName);



    }
    public void ShowPdf(string strFileName)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName);
        //Response.WriteFile(strFileName);
        Response.TransmitFile(strFileName);
        Response.End();
        Response.Flush();
        Response.Clear();
    }
}
We have created 1 more class file

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}
Above code snippet will help us to convert HTML page to pdf.

 Happy Coding !!


GridView to Pdf using iTextSharp

First of all you need to convert contents of gridview to Pdf. There is an third party dll:- iTextSharp dll which will help us to convert gridview contents to pdf.

1. Just Download iTextsharp lib. from http://sourceforge.net/projects/itextsharp/

2. Add 1 form in your project named as "pdf" then copy following design & Code behind code &  replace it in your code.

Currently we have taken 1 gridview & button on form.
You can bind your data to gridview as you required. I have just created dataset manually & assign it to gridview

Design Form
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="pdf.aspx.cs" Inherits="pdf" %>

<!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 runat="server">
    <title></title>
</head>
<body>
   <form id="form1" runat="server">
  <div>
      <asp:GridView ID="GridView1" runat="server">
      </asp:GridView>
      <asp:Button ID="btnExportToPdf" runat="server" OnClick="btnExportToPdf_Click"
          Text="Pdf" /></div>
</form>
</body>
</html>

Code Behind File
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Collections.Generic;

public partial class pdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = GetData();
            GridView1.DataBind();
        }
    }

    public DataSet GetData()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("Product");
        DataRow dr;
        dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
        dt.Columns.Add(new DataColumn("DisCount", typeof(Int32)));
        dt.Columns.Add(new DataColumn("SellPrice", typeof(Int32)));
        for (int i = 1; i <= 10; i++)
        {
            dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i * 2;
            dr[2] = 1 * 3;
            dt.Rows.Add(dr);
        }
        ds.Tables.Add(dt);
        Session["dt"] = dt;
        return ds;
    }

    protected void btnExportToPdf_Click(object sender, EventArgs e)
    {
        MyPage tmpPage = new MyPage();
        HtmlForm form = new HtmlForm();

        form.Controls.Add(GridView1);

        tmpPage.Controls.Add(form);
        StringWriter sw = new StringWriter();
        HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
        form.Controls[0].RenderControl(htmlWriter);
        string htmlContent = sw.ToString();
        Document document = new Document();
        // step 2:
        // we create a writer that listens to the document
        // and directs a PDF-stream to a file
        PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+ "\\Sample.pdf", FileMode.Create));
       

        // step 3: we open the document
        document.Open();

        // step 4: we add a paragraph to the document

        //document.Add(new Paragraph(htmlContent.ToString()));

        System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(htmlContent));

        //HtmlParser.Parse(document, _xmlr);
        using (TextReader sReader = new StringReader(sw.ToString()))
        {
            List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
            foreach (IElement elm in list)
            {
                document.Add(elm);
            }
        }

        // step 5: we close the document
        document.Close();

        //  Response.Write(document);
        string Path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Sample.pdf";
        ShowPdf(Path);
    }

    private void ShowPdf(string strS)
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "attachment; filename=" + strS);
        Response.TransmitFile(strS);
        Response.End();
        Response.Flush();
        Response.Clear();
    }

}

 We have created 1 more class file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// Summary description for MyPage
/// </summary>
public class MyPage : Page
{
    public override void VerifyRenderingInServerForm(Control control)
    {
        GridView grid = control as GridView;
        if (grid != null && grid.ID == "GridView1")
            return;
        else
            base.VerifyRenderingInServerForm(control);

    }
}

Above code snippet will help you to generate pdf.

 Happy Coding !!

Wednesday, July 13, 2011

To access crystal report control in code behind

To access crystal report control in code behind

Following 3 steps to access crystal report control & change value in codebehind
Steps:


1. Make an object of your crystal report.

    rptMyReport report = new rptMyReport();
2. Using object access control for which you want to do changes . cast control to TextObject


TextObject to =(TextObject) report.PageHeaderSection1.ReportObjects. ["textboxname"];

OR 

TextObject to = (TextObject)report.ReportDefinition.Sections["Section2"].ReportObjects["textboxname"];

3. Now using reference you can change the value of crystal report control .
          to.Text=newvalue;



Happy Coding!!





Thursday, March 10, 2011

Send email through gmail


Following snippet is for sending mail through gmail smtp server.

create 4 textboxes for to, from,subject & message. Dot Net has provided us a class System.Net.Mail.SmtpClient. with the help of this class we can send the email.

If your company have an email server you require to change following:
Gmails SMTP port is 587.
Gmails Host address is smtp.gmail.com
Give your username and password("username@gmail.com", "pwd") to make following code workable.


            System.Net.Mail.MailMessage mailmessage=new System.Net.Mail.MailMessage();
            mailmessage.Body = txtBody.Text;
            mailmessage.From = new System.Net.Mail.MailAddress( txtFrom.Text);
            mailmessage.To.Add(txtTo.Text);
            mailmessage.Subject = txtSubject.Text;
            mailmessage.IsBodyHtml = true;
            System.Net.Mail.SmtpClient smt = new System.Net.Mail.SmtpClient();
            smt.UseDefaultCredentials = false;

            smt.Credentials = new System.Net.NetworkCredential("username@gmail.com", "pwd");
            smt.Host = "smtp.gmail.com";
            smt.Port = 587;
            smt.EnableSsl = true;

            smt.Send(mailmessage);

Above code snippet will help us to send an email.

Happy Coding !! 

Wednesday, February 23, 2011

Font size changing while loading alert window through Javascript in response.write()

Problem:
I am using javscript to open a alert window when a button is clicked.
Here is the code in cs file :
Response.Write("<script>alert('hai')</script>");

Interesting thing is with the click of button, the font size changed (increased) in the original asp.net page; refreshing the screen brings back the original font size.

Solution
The above problem is caused because the script is coming outside the html in the rendered html page.

.Net Frame work has provide a class to manage client side scripts

Try like this.
// Define the name and type of the client scripts on the page.
Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(cstype, "name", "<script>alert('hai')</script>");
This code will help us to resolve our font size increase issue.


Happy Coding!!

Disable back using javascript in asp.net

After login we come to home page & after click on back button it should not move to login page
so we use following script to restrict it.

when we traverse through webpages its history is maintained. Don't forget to call setTimeout method
It works on Firefox , IE & Chrome  also
 <script type = "text/javascript" >
function disableback()
{
window.history.forward();
}
setTimeout("disableback()", 0);
</script>

Call above method on Body unload method on login page so when u move from login to home page after click on home's back button, we will be on same page that is on home page.
<body onunload="disableback()">
 now your back button problem will be solved......


Happy Coding!!

Tuesday, February 22, 2011

Focus particular textbox in page bydefault (like google) & on enter key press hit button from page(like google search button)

This are very easy things to do,

when we open any page and we want particular textbox contains cursor & after pressing enter button particular button gets clicked then do the following things.

In asp.net page contains a form tag, It contains defaultbutton & defaultfocus attributes set it as per your requirement

defaultbutton:= give your buttons name which u want to clicked
defaultfocus:= give control name for which you want focus after page load
<form id="form1" runat="server" defaultbutton="Button1" defaultfocus="TextBox1">
 Here  TextBox1 contains cursor & after press enter Button1's click event gets called.

Happy Coding !!