Creating PDF file using C#

Most of the forums, it’s a common question that how can we create PDF files from C#. Few days back I got a chance to work with iTextSharp library which helps to create PDF files from .Net. You can download the iTextSharp from sourceforge.net. It also supports HTML Parsing too.
Here is the code which converts and HTML File into PDF using iTextSharp libraries.

using System.Collections.Generic;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;

class Program
{
static void Main(string[] args)
    {
        //Creating the instance of the document object.
        Document doc = new Document();
        //Creating the PDF File
StreamWriter streamWriter = new StreamWriter(@"C:\Sample.pdf");
PdfWriter.GetInstance(doc, streamWriter.BaseStream);
        doc.Open();
IEnumerable<IElement> elements;
        //Reading the HTML Contents
using (StreamReader streamReader = new StreamReader(@"C:\SamplePage.htm"))
        {
            //Parsing HTML Contents.
elements = HTMLWorker.ParseToList(streamReader, new StyleSheet());
        }
foreach (IElement item in elements)
        {
            doc.Add(item);
        }
        //Custom Text which will be appended using Paragraph class.
        string paragraph = "This is custom text which will be appended";
        doc.Add(new Paragraph(paragraph));

        //Closing the document.
        doc.Close();
    }
}

Thanks to Rahul for providing initial inputs on iTextSharp library.

This entry was posted in .Net, .Net 3.0 / 3.5, ASP.Net and tagged , , , , , . Bookmark the permalink.

2 Responses to Creating PDF file using C#

  1. Jijo George says:

    iTextSharp give a good output for text based reports, getting blurry images in the PDF.

  2. Kanishka says:

    The External CSS doesnot works with PDF

    Thanks
    Kanishka

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>