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.
iTextSharp give a good output for text based reports, getting blurry images in the PDF.
The External CSS doesnot works with PDF
Thanks
Kanishka