65.9K
CodeProject is changing. Read more.
Home

Convert text into PDF using ASP.NET and C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.54/5 (13 votes)

Nov 9, 2011

CPOL
viewsIcon

102662

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:

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:

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;
}