Tuesday, September 14, 2010

Creating PDF with ASP.NET on fly

Last day I have given a situation where I have to create an HTML Invoice from database and send it through email with PDF of invoice as attachment. I found a very interesting and easy solution for this iTextPDF. A pdf library for creating pdf documents in c#.
In this example we will export  grid data in PDF format and send the same by mail as PDF attachment.

default.aspx
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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:Button ID="Button1" runat="server" onclick="Button1_Click"

Text="Export To PDF" />

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"

CellPadding="2" ForeColor="Black" GridLines="None">

<Columns>

<asp:BoundField DataField="country_id" HeaderText="Country ID" />

<asp:BoundField DataField="country_code" HeaderText="Country Code" />

<asp:BoundField DataField="country_name" HeaderText="Country Name" />

</Columns>

<FooterStyle BackColor="Tan" />

<PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"

HorizontalAlign="Center" />

<SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />

<HeaderStyle BackColor="Tan" Font-Bold="True" />

<AlternatingRowStyle BackColor="PaleGoldenrod" />

</asp:GridView>

</div>

</form>

</body>

</html> 
default.aspx.cs
using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Text;

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

using System.IO;

using System.Collections;

public partial class _Default : System.Web.UI.Page

{

#region BIND GRID

private void BindGrid()

{

//GETING DATA FROM SQL SERVER

string sql = "select country_id,country_code,country_name from country order by country_name";

GridView1.DataSource = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, sql, null);

GridView1.DataBind();

}

#endregion

#region EVENTS

protected void Button1_Click(object sender, EventArgs e)

{

WritePdf();

}

public override void VerifyRenderingInServerForm(Control control)

{

//don't throw any exception!

}

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack) { BindGrid(); }

}

#endregion

#region WRITE PDF

private void WritePdf()

{

StringBuilder _strRepeater = new StringBuilder();

Html32TextWriter _ObjHtm = new Html32TextWriter(new System.IO.StringWriter(_strRepeater));

GridView1.RenderControl(_ObjHtm);

string _str = _strRepeater.ToString();

//CREATE A UNIQUE NUMBER FOR PDF FILE NAMING USING DATE TIME STAMP

string filename = string.Format("{0:d7}", (DateTime.Now.Ticks / 10) % 10000000);

//CREATE DOCUMENT

Document document = new Document(new Rectangle(500f, 700f));

//SAVE DOCUMENT. CHECK IF YOU HAVE WRITE PERMISSION OR NOT

PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/pdfs/" + filename + ".pdf"), FileMode.Create));

document.Open();

List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(_str), null);

//add the collection to the document

for (int k = 0; k < htmlarraylist.Count; k++)

{

document.Add((IElement)htmlarraylist[k]);

}

document.Close();

//NOW SEND EMAIL TO USER WITH ATTACHMENT

string msg = "Hi this is test message";

email.SendMailAsHTML("Mail With PDF", "test@test.com", "abc@test.com", msg, Server.MapPath("~/pdfs/" + filename + ".pdf").ToString());

}

#endregion

} 
I have used this code in one of my online shopping cart, Manmeet Singh CEO of Yoginet Web solutions offering web designing , web development and SEO services for Individuals , small businesses and Corporates. Specialized in developing websites using latest HTML5 and designing Responsive websites.For more information about web solution please click here

Download Code

11 comments:

  1. i have solve my problem with this code.this is very help full fro html to PDF convert.

    ReplyDelete
  2. Hi All,
    I have the same problem but lil bit difference is there. actually i am generating a bus ticket but at the time of payment we want to send a ticket by email in pdf form to the customer. and ticket will genrate when payment has been done and new page will be open as ticket.aspx. but before open to this page we want to send the same ticket as pdf form with attachment through email...



    Waiting for ur reply....

    ReplyDelete
  3. Hi Amit,
    This you can do by using session variable (to hold the bus ticket HTML) or if you are storing the data in database then you can regenerate the data in HTML (from unique bus ticket ID) after getting the payment from user.
    Hope this helps!

    ReplyDelete
  4. Dear Amit,
    Plz use this type your code

    string _str = _strRepeater.ToString();
    string builder assign this string
    GridView1.RenderControl(_ObjHtm) comment this code.

    Try this if any problem then post your code........................

    ReplyDelete
  5. Your website look is not at all good for User.
    Please change it.

    ReplyDelete
  6. hye all,

    i need to generate a pdf containg question with answer key,in my application a leaner can give online test by selecting sub and no. of question he want to face... but at the same time if a learner want to give test and want to practice through question paper,then at that time i hv to generate a pdf file containing questions and answer key at that runtime,so plz suggest some idea how can i do this...

    ReplyDelete
  7. Thanks for sharing Information. We were looking to create PDF using ASP. Your code did helped us . We are web based company offering affordable web design services at discounted rates working under brand name Yoginet India . .

    ReplyDelete
  8. Thank you for your sharing. I want to post quickly but I do not know the way. Your article helps me, thank you so much Web Design Services India

    ReplyDelete
  9. Thanks for sharing information .. Please share more please . We at Mentors House also offers best website development services delhi ..

    ReplyDelete
  10. Thank you so much for this code because I was in trouble in a coding but now my problem is solved by you. web developer in delhi

    ReplyDelete
  11. Some time ago I had a problem in coding but I left that problem, suddenly I read a blog and I get rid of from that trouble actually I have website of ice cube machine and thanks for this useful coding.

    ReplyDelete