Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Convert text into PDF using ASP.NET and C#

4.54/5 (13 votes)
16 Dec 2011CPOL 102.7K  
Text to PDF Convert

Quote: First of all, download the DLL file (itextsharp). You can download it from here. Then open a new project in ASP.NET where language is C# .NET. Right click on the project name and select "Add Reference". Then browse the DLL file. Now go to your .aspx page and drag a label or textbox and a button. Our aim is, there will be some text in the label or textbox and when we click the button, it will create a PDF file having the text in it. Here, I am using a Label for HTML format and my label name is lblArticle. And I have created a folder in my project named pdf.


Now go to your .cs page, add the namespace, and copy the following code:


C#
using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.xml; 

Then go to your button click event and copy the following code:


C#
Document document = new Document();

try
{ 
    PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/") + "pdf/" + "print.pdf", FileMode.Create));
    document.Open();

    List<ielement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(
                      new StringReader(lblArticle.Text), null);

    for (int k = 0; k < htmlarraylist.Count; k++)
    {
        document.Add((IElement)htmlarraylist[k]);

    }

    Paragraph mypara = new Paragraph(); 
    document.Add(mypara);

    document.Close();

    Response.Redirect("~/pdf/print.pdf");
}
catch (Exception ex)
{
    lblArticle.Text = ex.Message;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)