Sunday, July 21, 2013

How to Create Controls Dynamically in code behind files and Save in database using asp.net

Referred URL - http://www.aspdotnet-suresh.com/2010/09/how-to-create-controls-dynamically-in.html

Introduction:

Here I will explain how to generate the controls dynamically in code behind using asp.net

Description:

Hi here I will explain how to generate the controls dynamically in asp.net code behind
First design the your aspx page with one panel like this 


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>


After that write the following code in page load method like this 


protected void Page_Load(object sender, EventArgs e)
{
Table tbldynamic = new Table();
for (int i = 0; i < 5; i++)
{
TableCell tc = new TableCell();
TableRow tr = new TableRow();
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "chkDynamicCheckBox" + i;
_checkbox.Text = "Checkbox" + i;
tc.Controls.Add(_checkbox);
tr.Cells.Add(tc);
tbldynamic.Rows.Add(tr);
}
Panel1.Controls.Add(tbldynamic);
}


Now run application you will see dynamically generated checkboxes like that we can generate controls dynamically.
 
To implement this concept first design table in database and give name as UserDetails as shown below

Column Name
Data Type
Allow Nulls
UserId
int(set identity property=true)
No
UserName
varchar(50)
Yes
Email
varchar(100)
Yes
After completion table design write the following code in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Create controls dynamically in asp.net and handle button click events</title>
</head>
<body>
<form id="form2" runat="server">
<div>
<asp:Panel ID="pnlInfo" runat="server">
</asp:Panel>
</div>
</form>
</body>
</html>
After completion of aspx page design add the following namespaces in code behind

C# code


using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After add namespaces write the following code in code behind like as shown below


protected void Page_Load(object sender, EventArgs e)
{
Table tbldynamic = new Table();
TableCell tc=new TableCell();
TableCell tc1=new TableCell();
TableRow tr = new TableRow();
Label lblName =new Label();
lblName.ID = "lblName";
lblName.Text = "UserName:";
tc.Controls.Add(lblName);
TextBox txtName=new TextBox();
txtName.ID = "txtName";
tc1.Controls.Add(txtName);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
tc=new TableCell();
tc1=new TableCell();
tr=new TableRow();
Label lblEmail = new Label();
lblEmail.ID = "lblEmail";
lblEmail.Text = "Email:";
tc.Controls.Add(lblEmail);
TextBox txtEmail = new TextBox();
txtEmail.ID = "txtEmail";
tc1.Controls.Add(txtEmail);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
tc = new TableCell();
tc1 = new TableCell();
tr = new TableRow();
Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Submit";
btnSubmit.Click += new System.EventHandler(btnSubmit_click);
tc1.Controls.Add(btnSubmit);
tr.Cells.Add(tc);
tr.Cells.Add(tc1);
tbldynamic.Rows.Add(tr);
pnlInfo.Controls.Add(tbldynamic);
}
// Dynamic button click event which is used to save values in database
protected void btnSubmit_click(object sender, EventArgs e)
{
String str = string.Empty;
TextBox txtUserName = (TextBox)pnlInfo.FindControl("txtName");
// str = txtUserName.Text;
TextBox txtEmail = (TextBox)pnlInfo.FindControl("txtEmail");
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
using (SqlCommand cmd =new SqlCommand("INSERT INTO UserDetails(UserName,Email) VALUES(@name,@mail)",con))
{
con.Open();
cmd.Parameters.AddWithValue("@name", txtUserName.Text);
cmd.Parameters.AddWithValue("@mail", txtEmail.Text);
cmd.ExecuteNonQuery();
txtEmail.Text = string.Empty;
txtUserName.Text = string.Empty;
ClientScript.RegisterClientScriptBlock(this.GetType(), "btn","<script type = 'text/javascript'>alert('UserDetails saved Successfully');</script>");
}
}
}

VB.NET Code

Imports System.Data.SqlClient
Imports System.Web.UI.WebControls
Partial Class Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

Dim tbldynamic As New Table()
Dim tc As New TableCell()
Dim tc1 As New TableCell()
Dim tr As New TableRow()
Dim lblName As New Label()
lblName.ID = "lblName"
lblName.Text = "UserName:"
tc.Controls.Add(lblName)
Dim txtName As New TextBox()
txtName.ID = "txtName"
tc1.Controls.Add(txtName)
tr.Cells.Add(tc)
tr.Cells.Add(tc1)
tbldynamic.Rows.Add(tr)
tc = New TableCell()
tc1 = New TableCell()
tr = New TableRow()
Dim lblEmail As New Label()
lblEmail.ID = "lblEmail"
lblEmail.Text = "Email:"
tc.Controls.Add(lblEmail)
Dim txtEmail As New TextBox()
txtEmail.ID = "txtEmail"
tc1.Controls.Add(txtEmail)
tr.Cells.Add(tc)
tr.Cells.Add(tc1)
tbldynamic.Rows.Add(tr)
tc = New TableCell()
tc1 = New TableCell()
tr = New TableRow()
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Submit"
AddHandler btnSubmit.Click, AddressOf btnSubmit_click
tc1.Controls.Add(btnSubmit)
tr.Cells.Add(tc)
tr.Cells.Add(tc1)
tbldynamic.Rows.Add(tr)
pnlInfo.Controls.Add(tbldynamic)
End Sub
' Dynamic button click event which is used to save values in database
Protected Sub btnSubmit_click(ByVal sender As Object, ByVal e As EventArgs)
Dim str As [String] = String.Empty
Dim txtUserName As TextBox = DirectCast(pnlInfo.FindControl("txtName"), TextBox)
' str = txtUserName.Text;
Dim txtEmail As TextBox = DirectCast(pnlInfo.FindControl("txtEmail"), TextBox)
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
Using cmd As New SqlCommand("INSERT INTO UserDetails(UserName,Email) VALUES(@name,@mail)", con)
con.Open()
cmd.Parameters.AddWithValue("@name", txtUserName.Text)
cmd.Parameters.AddWithValue("@mail", txtEmail.Text)
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
End Class
Demo


Creating a Currency Masked TextBox with On-the-Fly Currency Formatting

Referred URL :
http://scottonwriting.net/sowblog/archive/2011/06/25/creating-a-currency-masked-textbox-with-on-the-fly-currency-formatting.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed:+ScottOnWriting+(Scott+on+Writing)

Allowing Only Currency-Related Characters In a TextBox

There are a number of existing masked input plugins for jQuery. After trying some out I decided to roll my own JavaScript functions. I intend to come back to these and turn them into jQuery plugins, but for now they’re just JavaScript functions. As you can see in the script below, I created four functions:
  • numbersOnly – allows just number inputs, whether they are from the letters at the top of the keyboard or from the number pad.
  • numbersAndCommasOnly – allows number inputs and commas.
  • decimalsOnly – allows numbers, commas, and periods (either from the main keyboard or the number pad).
  • currenciesOnly – allows numbers, commas, periods, and the dollar sign.
In addition to the allowed characters discussed above, the functions also permit “special character key codes,” namely Delete, Backspace, left arrow, right arrow, Home, End and Tab. What keycodes are valid are listed in the variables at the top of the script; see Javascript Char Codes for a table listing the keys and their corresponding key codes. Here is the script of interest:
// JavaScript I wrote to limit what types of input are allowed to be keyed into a textbox 
var allowedSpecialCharKeyCodes = [46,8,37,39,35,36,9];
var numberKeyCodes = [44, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105];
var commaKeyCode = [188];
var decimalKeyCode = [190,110];

function numbersOnly(event) {
    var legalKeyCode =
        (!event.shiftKey && !event.ctrlKey && !event.altKey)
            &&
        (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, numberKeyCodes) >= 0);

    if (legalKeyCode === false)
        event.preventDefault();
}

function numbersAndCommasOnly(event) {
    var legalKeyCode =
        (!event.shiftKey && !event.ctrlKey && !event.altKey)
            &&
        (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, numberKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, commaKeyCode) >= 0);

    if (legalKeyCode === false)
        event.preventDefault();
}

function decimalsOnly(event) {
    var legalKeyCode =
        (!event.shiftKey && !event.ctrlKey && !event.altKey)
            &&
        (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, numberKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, commaKeyCode) >= 0
            ||
        jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);

    if (legalKeyCode === false)
        event.preventDefault();
}

function currenciesOnly(event) {
    var legalKeyCode =
        (!event.shiftKey && !event.ctrlKey && !event.altKey)
            &&
        (jQuery.inArray(event.keyCode, allowedSpecialCharKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, numberKeyCodes) >= 0
            ||
        jQuery.inArray(event.keyCode, commaKeyCode) >= 0
            ||
        jQuery.inArray(event.keyCode, decimalKeyCode) >= 0);

    // Allow for $
    if (!legalKeyCode && event.shiftKey && event.keyCode == 52)
        legalKeyCode = true;

    if (legalKeyCode === false)
        event.preventDefault();
}

My script is, admittedly, very US-centric. I have not tested the key codes with a non-English keyboard and for currencies I only allow a dollar sign. For the project I wrote this script for this is (currently) a non-issue since it is used within the corporate firewall and all sales are domestic, but clearly the above script would not work as well for international settings.

Applying the Currency Masking Script to a TextBox on the Page


With the above script in place you can have a textbox on the page mask its input by having the appropriate function called in response to the keydown event. The following jQuery syntax wires up this logic to all single-line textboxes that have the CSS class currenciesOnly.
$(document).ready(function () {
    $("input[type=text].currenciesOnly").live('keydown', currenciesOnly);
});

That’s it!

Formatting the Just-Entered Currency


Another requirement my client had was to format the just-entered number as a currency. That is, to change the user’s input – say, 45000 – to a formatted value like $45,000.00 immediately after their tabbed out of the textbox. To accomplish this I used Ben Dewey’s jQuery Format Currency Plugin, which you can see a demo of athttp://www.bendewey.com/code/formatcurrency/demo/. This plugin adds a formatCurrency function that you can call on a set of elements returned by a jQuery selector.
To use this plugin I updated the $(document).ready event handler shown above to also call theformatCurrency function on blur:
$(document).ready(function () {
    $("input[type=text].currenciesOnly").live('keydown', currenciesOnly)
                        .live('blur', 
                                 function () { 
                                     $(this).formatCurrency(); 
                                 }
                              );
});

In short, whenever a textbox with a CSS class of currenciesOnly is blurred, the just-blurred textbox’s inputs are formatted as a currency thanks to the formatCurrency function

Dynamic Image Generation, ASP.NET Controllers, Routing, IHttpHandlers, and runAllManagedModulesForAllRequests

Referred URL
http://www.hanselman.com/blog/BackToBasicsDynamicImageGenerationASPNETControllersRoutingIHttpHandlersAndRunAllManagedModulesForAllRequests.aspx

Often folks want to dynamically generate stuff with ASP.NET. The want to dynamically generate PDFs, GIFs, PNGs, CSVs, and lots more. It's easy to do this, but there's a few things to be aware of if you want to keep things as simple and scalable as possible. You need to think about the whole pipeline as any HTTP request comes in. The goal is to have just the minimum number of things run to do the job effectively and securely, but you also need to think about "who sees the URL and when." A timeline representation of the ASP.NET pipeline This diagram isn't meant to be exhaustive, but rather give a general sense of when things happen. Modules can see any request if they are plugged into the pipeline. There are native modules written in C++ and managed modules written in .NET. Managed modules are run anytime a URL ends up being processed by ASP.NET or if "RAMMFAR" is turned on. <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> </system.webServer> You want to avoid having this option turned on if your configuration and architecture can handle it. This does exactly what it says. All managed modules will run for all requests. That means *.* folks. PNGs, PDFs, everything including static files ends up getting seen by ASP.NET and the full pipeline. If you can let IIS handle a request before ASP.NET sees it, that's better. Remember that the key to scaling is to do as little as possible. You can certainly make a foo.aspx in ASP.NET Web Forms page and have it dynamically generate a graphic, but there's some non-zero amount of overhead involved in the creation of the page and its lifecycle. You can make a MyImageController in ASP.NET MVC but there's some overhead in the Routing that chopped up the URL and decided to route it to the Controller. You can create just an HttpHandler or ashx. The result in all these cases is that an image gets generated but if you can get in and get out as fast as you can it'll be better for everyone. You can route the HttpHandler with ASP.NET Routing or plug it into web.config directly.
Works But...Dynamic Images with RAMMFAR and ASP.NET MVC
A customer wrote me who was using ASP.NET Routing (which is an HttpModule) and a custom routing handler to generate images like this: routes.Add(new Route("images/mvcproducts/{ProductName}/default.png", new CustomPNGRouteHandler())); Then they have a IRouteHandler that just delegates to an HttpHandler anyway: public class CustomPNGRouteHandler : IRouteHandler { public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { return new CustomPNGHandler(requestContext); } } Note the {ProductName} route data in the route there. The customer wants to be able to put anything in that bit. if I visithttp://localhost:9999/images/mvcproducts/myproductname/default.png I see this image... A dynamically generated PNG from ASP.NET Routing, routed to an IHttpHandler Generated from this simple HttpHandler: public class CustomPNGHandler : IHttpHandler { public bool IsReusable { get { return false; } } protected RequestContext RequestContext { get; set; } public CustomPNGHandler():base(){} public CustomPNGHandler(RequestContext requestContext) { this.RequestContext = requestContext; } public void ProcessRequest(HttpContext context) { using (var rectangleFont = new Font("Arial", 14, FontStyle.Bold)) using (var bitmap = new Bitmap(320, 110, PixelFormat.Format24bppRgb)) using (var g = Graphics.FromImage(bitmap)) { g.SmoothingMode = SmoothingMode.AntiAlias; var backgroundColor = Color.Bisque; g.Clear(backgroundColor); g.DrawString("This PNG was totally generated", rectangleFont, SystemBrushes.WindowText, new PointF(10, 40)); context.Response.ContentType = "image/png"; bitmap.Save(context.Response.OutputStream, ImageFormat.Png); } } } The benefits of using MVC is that handler is integrated into your routing table. The bad thing is that doing this simple thing requires RAMMFAR to be on. Every module sees every request now so you can generate your graphic. Did you want that side effect? The bold is to make you pay attention, not scare you. But you do need to know what changes you're making that might affect the whole application pipeline.
(As an aside, if you're a big site doing dynamic images, you really should have your images on their own cookieless subdomain in the cloud somewhere with lots of caching, but that's another article).
So routing to an HttpHandler (or an MVC Controller) is an OK solution but it's worth exploring to see if there's an easier way that would involve fewer moving parts. In this case the they really want the file to have the extension *.png rather than *.aspx (page) or *.ashx (handler) as it they believe it affects their image's SEO in Google Image search.
Better: Custom HttpHandlers
Remember that HttpHandlers are targeted to a specific path, file or wildcard and HttpModules are always watching. Why not use an HttpHandler directly and plug it in at the web.config level and set runAllManagedModulesForAllRequests="false"? <system.webServer> <handlers> <add name="pngs" verb="*" path="images/handlerproducts/*/default.png" type="DynamicPNGs.CustomPNGHandler, DynamicPNGs" preCondition="managedHandler"/> </handlers> <modules runAllManagedModulesForAllRequests="false" /> </system.webServer> Note how I have a * there in part of the URL? Let's try hitting http://localhost:37865/images/handlerproducts/myproductname/default.png. It still works. A dynamically generated PNG from an ASP.NET IHttpHandler This lets us not only completely bypass the managed ASP.NET Routing system but also remove RAMMFAR so fewer modules are involved for other requests. By default, managed modules will only run for requests that ended up mapped to the managed pipeline and that's almost always requests with an extension. You may need to be aware of routing if you have a "greedy route" that might try to get ahold of your URL. You might want an IgnoreRoute. You also need to be aware of modules earlier in the process that have a greedy BeginRequest. The customer could setup ASP.NET and IIS to route request for *.png to ASP.NET, but why not be as specific as possible so that the minimum number of requests is routed through the managed pipeline? Don't do more work than you need to.
What about extensionless URLs?
Getting extensionless URLs working on IIS6 was tricky before and lots of been written on it. Early on in IIS6 and ASP.NET MVC you'd map everything *.* to managed code. ASP.NET Routing used to require RAMFARR set to true until the Extensionless URL feature was created. Extentionless URLs support was added in this KB http://support.microsoft.com/kb/980368 and ships with ASP.NET MVC 4. If you have ASP.NET MVC 4, you have Extentionless URLs on your development machine. But your server may not. You may need to install this hotfix, or turn on RAMMFAR. I would rather you install the update than turn on RAMMFAR if you can avoid it. The Run All Modules options is really a wildcard mapping. Extensionless URLs exists so you can have URLs like /home/about and not /home/about.aspx. It exists to get URLs without extensions to be seen be the managed pipelines while URLs with extensions are not seen any differently. The performance benefits of Extensionless URLs over RAMMFAR are significant. If you have static files like CSS, JS and PNG files you really want those to be handled by IIS (and HTTP.SYS) for speed. Don't let your static files get mapped to ASP.NET if you can avoid it.
Conclusion
When you're considering any solution within the ASP.NET stack (or "One ASP.NET" as I like to call it)... The complete ASP.NET stack with MVC, Web Pages, Web Forms and more called out in a stack of boxes ...remember that it's things like IHttpHandler that sit at the bottom and serve one request (everything comes from IHttpHandler) while it's IHttpModule that's always watching and can see every request. In other words, and HttpHandler sees the ExecuteRequestHandler event which is just one event in the pipeline, while HttpModules can see every event they subscribe to. HttpHandlers and Modules are at the bottom of the stack

Saturday, July 20, 2013

iTextSharp — few C# examples.

Referred URL - http://simpledotnetsolutions.wordpress.com/2012/04/08/itextsharp-few-c-examples/

iTextSharp is open source PDF solution. In most of the examples below, I tried to alter,copy a template PDF and then save it into a brand new output PDF file. It’s easy to work with PDFs , when we have a basic template (created externally using Adobe/OpenOffice) in place, –  instead of generating a new PDF from scratch. For any data which needs to be modified, I do it in the web page and then save the modified data/results to a pdf file. This prevents the need, for user to modify the pdf form fields.

http://www.itextpdf.com/book/chapter.php?id=1

This web link was the basic source, for all my scenarios. (Note: The examples in iTextSharp site are in java)


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 iTextSharp.text.pdf;
using System.Data;
using System.Text;
using iTextSharp.text.pdf.parser;
using System.util.collections;
using iTextSharp.text;
using System.Net.Mail;

public partial class PDFScenarios : System.Web.UI.Page
{
public string P_InputStream = "~/MyPDFTemplates/ex1.pdf";
public string P_InputStream2 = "~/MyPDFTemplates/ContactInfo.pdf";
public string P_InputStream3 = "~/MyPDFTemplates/MulPages.pdf";
public string P_InputStream4 = "~/MyPDFTemplates/CompanyLetterHead.pdf";
public string P_OutputStream = "~/MyPDFOutputs/ex1_1.pdf";

//Read all 'Form values/keys' from an existing multi-page PDF document
public void ReadPDFformDataPageWise()
{
PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
AcroFields form = reader.AcroFields;
try
{
for (int page = 1; page <= reader.NumberOfPages; page++)
{
    foreach (KeyValuePair<string, AcroFields.Item> kvp in form.Fields)
    {
        switch (form.GetFieldType(kvp.Key))
        {
            case AcroFields.FIELD_TYPE_CHECKBOX:
            case AcroFields.FIELD_TYPE_COMBO:
            case AcroFields.FIELD_TYPE_LIST:
            case AcroFields.FIELD_TYPE_RADIOBUTTON:
            case AcroFields.FIELD_TYPE_NONE:
            case AcroFields.FIELD_TYPE_PUSHBUTTON:
            case AcroFields.FIELD_TYPE_SIGNATURE:
            case AcroFields.FIELD_TYPE_TEXT:
                int fileType = form.GetFieldType(kvp.Key);
                string fieldValue = form.GetField(kvp.Key);
                string translatedFileName = form.GetTranslatedFieldName(kvp.Key);
                break;
        }
    }
}
}
catch
{
}
finally
{
    reader.Close();
}
}


//Read and alter form values for only second and 
//third page of an existing multi page PDF doc.
//Save the changes in a brand new pdf file.
public void ReadAlterPDFformDataInSelectedPages()
{
PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
reader.SelectPages("1-2"); //Work with only page# 1 & 2
using (PdfStamper stamper = new PdfStamper(reader, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create)))
{
    AcroFields form = stamper.AcroFields;
    var fieldKeys = form.Fields.Keys;
    foreach (string fieldKey in fieldKeys)
    {
        //Replace Address Form field with my custom data
        if (fieldKey.Contains("Address"))
        {
            form.SetField(fieldKey, "MyCustomAddress");
        }
    }
    //The below will make sure the fields are not editable in
    //the output PDF.
    stamper.FormFlattening = true;
}
}


//Extract text from an existing PDF's second page.
private string ExtractText()
{
    PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
    string txt =  PdfTextExtractor.GetTextFromPage(reader, 2, new LocationTextExtractionStrategy());
    return txt;
}


//Create a brand new PDF from scratch and without a template
private void CreatePDFNoTemplate()
{
    Document pdfDoc = new Document();
    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(Server.MapPath(P_OutputStream), FileMode.OpenOrCreate));

    pdfDoc.Open();
    pdfDoc.Add(new Paragraph("Some data"));
    PdfContentByte cb = writer.DirectContent;
    cb.MoveTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height / 2);
    cb.LineTo(pdfDoc.PageSize.Width / 2, pdfDoc.PageSize.Height);
    cb.Stroke();

    pdfDoc.Close(); 
}


private void fillPDFForm()
{
    string formFile = Server.MapPath(P_InputStream);
    string newFile = Server.MapPath(P_OutputStream);
    PdfReader reader = new PdfReader(formFile);
    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(newFile, FileMode.Create)))
    {
        AcroFields fields = stamper.AcroFields;

        // set form fields
        fields.SetField("name", "John Doe");
        fields.SetField("address", "xxxxx, yyyy");
        fields.SetField("postal_code", "12345");
        fields.SetField("email", "johndoe@xxx.com");

        // flatten form fields and close document
        stamper.FormFlattening = true;
        stamper.Close();
    }
}


//Helper functions
private void SendEmail(MemoryStream ms)
{
    MailAddress _From = new MailAddress("XXX@domain.com");
    MailAddress _To = new MailAddress("YYY@a.com"); 
    MailMessage email = new MailMessage(_From, _To); 
    Attachment attach = new Attachment(ms,  new System.Net.Mime.ContentType("application/pdf")); 
    email.Attachments.Add(attach);  
    SmtpClient mailSender = new SmtpClient("Gmail-Server"); 
    mailSender.Send(email);  
}


private void DownloadAsPDF(MemoryStream ms)
{
    Response.Clear();
    Response.ClearContent();
    Response.ClearHeaders();
    Response.ContentType = "application/pdf";
    Response.AppendHeader("Content-Disposition", "attachment;filename=abc.pdf");
    Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
    Response.OutputStream.Flush();
    Response.OutputStream.Close();
    Response.End();
    ms.Close();
}


//Working with Memory Stream and PDF
public void CreatePDFFromMemoryStream()
{
    //(1)using PDFWriter
    Document doc = new Document();
    MemoryStream memoryStream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
    doc.Open();
    doc.Add(new Paragraph("Some Text"));
    writer.CloseStream = false;
    doc.Close();
    //Get the pointer to the beginning of the stream. 
    memoryStream.Position = 0;
    //You may use this PDF in memorystream to send as an attachment in an email
    //OR download as a PDF
    SendEmail(memoryStream);
    DownloadAsPDF(memoryStream);

    //(2)Another way using PdfStamper
    PdfReader reader = new PdfReader(Server.MapPath(P_InputStream2));
    using (MemoryStream ms = new MemoryStream())
    {
        PdfStamper stamper = new PdfStamper(reader, ms);
        AcroFields fields = stamper.AcroFields;
        fields.SetField("SomeField", "MyValueFromDB");
        stamper.FormFlattening = true;
        stamper.Close();
        SendEmail(ms);
    }
}



//Burst-- Make each page of an existing multi-page PDF document 
//as another brand new PDF document
private void PDFBurst()
{
    string pdfTemplatePath = Server.MapPath(P_InputStream3);
    PdfReader reader = new PdfReader(pdfTemplatePath);
    //PdfCopy copy;
    PdfSmartCopy copy;
    for (int i = 1; i < reader.NumberOfPages; i++)
    {
        Document d1 = new Document();
        copy = new PdfSmartCopy(d1, new FileStream(Server.MapPath(P_OutputStream).Replace(".pdf", i.ToString() + ".pdf"), FileMode.Create));
        d1.Open();
        copy.AddPage(copy.GetImportedPage(reader, i));
        d1.Close();
    }
}

//Copy a set of form fields from an existing PDF template/doc
//and keep appending to a brand new PDF file.
//The copied set of fields will have different values.
private void AppendSetOfFormFields()
{
    PdfCopyFields _copy = new PdfCopyFields(new FileStream(Server.MapPath(P_OutputStream), FileMode.Create));
    _copy.AddDocument(new PdfReader(a1("1")));
    _copy.AddDocument(new PdfReader(a1("2")));
    _copy.AddDocument(new PdfReader(new FileStream(Server.MapPath("~/MyPDFTemplates/Myaspx.pdf"), FileMode.Open)));
    _copy.Close();
}
//ConcatenateForms
private byte[] a1(string _ToAppend)
{
    using (var existingFileStream = new FileStream(Server.MapPath(P_InputStream), FileMode.Open))
    using (MemoryStream stream = new MemoryStream())
    {
        // Open existing PDF
        var pdfReader = new PdfReader(existingFileStream);
        var stamper = new PdfStamper(pdfReader, stream);
        var form = stamper.AcroFields;
        var fieldKeys = form.Fields.Keys;

        foreach (string fieldKey in fieldKeys)
        {
            form.RenameField(fieldKey, fieldKey + _ToAppend);
        }
        // "Flatten" the form so it wont be editable/usable anymore
        stamper.FormFlattening = true;
        stamper.Close();
        pdfReader.Close();
        return stream.ToArray();
    }
}


//Working with Image
private void AddAnImage()
{
    using (var inputPdfStream = new FileStream(@"C:\MyInput.pdf", FileMode.Open))
    using (var inputImageStream = new FileStream(@"C:\img1.jpg", FileMode.Open))
    using (var outputPdfStream = new FileStream(@"C:\MyOutput.pdf", FileMode.Create))
    {
        PdfReader reader = new PdfReader(inputPdfStream);
        PdfStamper stamper = new PdfStamper(reader, outputPdfStream);
        PdfContentByte pdfContentByte = stamper.GetOverContent(1);
        var image = iTextSharp.text.Image.GetInstance(inputImageStream);
        image.SetAbsolutePosition(1, 1);
        pdfContentByte.AddImage(image);
        stamper.Close();
    }

}


//Add Company Letter-Head/Stationary to an existing pdf
private void AddCompanyStationary()
{
    PdfReader reader = new PdfReader(Server.MapPath(P_InputStream2));
    PdfReader s_reader = new PdfReader(Server.MapPath(P_InputStream4));

    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create)))
    {
        PdfImportedPage page = stamper.GetImportedPage(s_reader, 1);
        int n = reader.NumberOfPages;
        PdfContentByte background;
        for (int i = 1; i <= n; i++)
        {
            background = stamper.GetUnderContent(i);
            background.AddTemplate(page, 0, 0);
        }
        stamper.Close();
    }
}


//Create a new PDF document by copying only 2nd page from an existing PDF document.
//Also add a date on the top-left corner.
private void AddText()
{
    //Method 1:
    PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
    using (Document document = new Document())
    {
        using (PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create)))
        {
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 2);

            document.NewPage();
            cb.AddTemplate(page, 0, 0);
            document.Add(new Paragraph(DateTime.Now.ToShortDateString()));
            document.Close();
        }
    }

    //Method 2:
    PdfReader reader2 = new PdfReader(Server.MapPath(P_InputStream3));
    using (PdfStamper stamper = new PdfStamper(reader, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create)))
    {
        stamper.RotateContents = false;
        PdfContentByte canvas = stamper.GetOverContent(2);
        ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase(DateTime.Now.ToShortDateString()), 0, 0, 0);
        stamper.Close();
    }
}




//DataSheets: Copy 2 pages from one PDF to another brand new PDF.
//Also alter some form data
private void CreatePDFByCopy()
{
    using (Document document = new Document())
    {
        using (PdfSmartCopy copy = new PdfSmartCopy(document, new FileStream(Server.MapPath(P_OutputStream), FileMode.Create)))
        {
            document.Open();
            for (int i = 0; i < 2; ++i)
            {
                PdfReader reader = new PdfReader(AddDataSheets("Some Text" + i.ToString()));
                copy.AddPage(copy.GetImportedPage(reader, 1));
            }
        }
    }
}


public byte[] AddDataSheets(string _data)
{
    string pdfTemplatePath = Server.MapPath(P_InputStream2);
    PdfReader reader = new PdfReader(pdfTemplatePath);
    using (MemoryStream ms = new MemoryStream())
    {
        using (PdfStamper stamper = new PdfStamper(reader, ms))
        {
            AcroFields form = stamper.AcroFields;
            var fieldKeys = form.Fields.Keys;
            foreach (string fieldKey in fieldKeys)
            {
                //Change some data
                if (fieldKey.Contains("Address"))
                {
                    form.SetField(fieldKey, _data);
                }
            }        
            stamper.FormFlattening = true;
        }
        return ms.ToArray();
    }
}