Thursday, May 14, 2009

Create PDF from Text input in C# using iTextSharp.dll

We can Create PDF file from text data using many third party dlls.
iTextSharp is one of them Which provide many function to manipulate this type of stuff.
you have to add referance of iTextSharp.dll to your project. and add iTextSharp.text.pdf , iTextSharp.text in page directive.

public partial class CreatePDF : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btnCreate.Click += new EventHandler(btnCreate_Click);
}
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Enter data and click to create pdf....");
}
public void btnCreate_Click(object sender, EventArgs e)
{
string iCreatePDFdir = Server.MapPath("~/") + "iCreatePDF\\PDFTest";
string iCreatePDFTest = iCreatePDFdir + "\\PDFTest.pdf";
Directory.CreateDirectory(iCreatePDFdir);
Document pdfDocCreatePDF = new Document();
PdfWriter.GetInstance(pdfDocCreatePDF, new FileStream(iCreatePDFTest, FileMode.Create));
pdfDocCreatePDF.Open();
pdfDocCreatePDF.Add(new Paragraph(txtContent.Text));
pdfDocCreatePDF.Close();
Response.Redirect("~/iCreatePDF/PDFTest/PDFTest.pdf");
}
}


This the demo code for that.

Thanks.