Generating PDF document in .NET using iTextSharp Library
well, it was just yesterday that I was looking into converting html to pdf programmatically in .NET 2.0. After some googling, I came up to the iTextSharp library at SourceForge.
Just built an application to test run this iTextSharp library. so here’s the code for the “Hello world” application.
private void HelloWorldPdf()
{
try
{
iTextSharp.text.Document oDoc = new iTextSharp.text.Document();
PdfWriter.GetInstance(oDoc, new FileStream(“HelloWorld.pdf”, FileMode.Create));
oDoc.Open();
oDoc.Add(new Paragraph(“Hello World!”));
oDoc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
It works!, Then I tried inserting an image in the pdf document and that worked too.
private void InsertImageinPDF()
{
//Already existing file
string pdfTemplate = “HelloWorld.pdf”;//@”C:\PDFFileSoftware\PdfGenerator_CS\PdfGenerator_CS\PdfGenerator\1_Form SS-4 (2007).pdf”;
//@”c:\Temp\PDF\fw4.pdf”;
string newFile = @”completed_fw4.pdf”;//c:\Temp\PDF\
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
string chartLoc = string.Empty;
chartLoc = @”C:\Documents and Settings\Imran Akram\My Documents\My Pictures\TheDeparted.jpg”;//@”C:\Temp\PDF\IMG_3746.jpg”;//pplLogoSmall.jpg”;
iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartLoc);
iTextSharp.text.pdf.PdfContentByte underContent;
iTextSharp.text.Rectangle rect;
try
{
Single X, Y; int pageCount = 0;
rect = pdfReader.GetPageSizeWithRotation(1);
if (chartImg.Width > rect.Width || chartImg.Height > rect.Height)
{
chartImg.ScaleToFit(rect.Width, rect.Height);
X = (rect.Width – chartImg.ScaledWidth) / 2;
Y = (rect.Height – chartImg.ScaledHeight) / 2;
}
else
{
X = (rect.Width – chartImg.Width) / 2;
Y = (rect.Height – chartImg.Height) / 2;
} chartImg.SetAbsolutePosition(X, Y);
pageCount = pdfReader.NumberOfPages;
for (int i = 1; i <= pageCount; i++)
{
underContent = pdfStamper.GetOverContent(i);//.GetUnderContent(i);
underContent.AddImage(chartImg);
}
pdfStamper.Close();
pdfReader.Close();
}
catch (Exception ex)
{
throw ex;
}
}
OKAY So far so good, but what about the thing I needed the most…. Rendering Html to pdf!! And guess what I was quite disappointed. The HtmlParser is just not strong enough. It gets mad even if it gets a br tag, your code has to be absolutely XHTML conformant or it will give u nothing. But for your interest, I’m giving you guys the code.
/// <summary>
/// Creates the PDF document with a given content at a given location.
/// </summary>
/// <param name=”strFilePath”>The file path to write the new PDF to.</param>
/// <param name=”strContent”>Content in HTML to write to the PDF.</param>
public static void CreatePDFDocument(String strFilePath, String strContent)
{
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(strFilePath, FileMode.Create));
//XmlTextReader reader = new XmlTextReader(new StringReader(strContent));
//reader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
//HtmlParser.Parse(document, reader);
System.Xml.XmlTextReader _xmlr = new System.Xml.XmlTextReader(new StringReader(@”<html><body>This is my <bold>test</bold> string</body></html>”));
HtmlParser.Parse(document, _xmlr);
}
catch (Exception e)
{
throw e;
}
}
I gotta say, the HtmlParser is really vulnerable. So, I decided to use ABCPdf instead.


Hi Imran -
Would you mind giving a newbie a hand?
I’ve been trying to find a comprehensible iTextSharp example on the internet and yours looked very straightforward.
Unfortunately I’m stumped with a basic problem.
I add the iTextSharp.dll to my app. as a reference and put “using iTextSharp;” at the top.
The first line in your example compiles fine:-
iTextSharp.text.Document oDoc = new iTextSharp.text.Document();
but then when I add in the next line:-
PdfWriter.GetInstance(oDoc, new FileStream(”HelloWorld.pdf”, FileMode.Create));
It complains that PdfWriter doesn’t exist.
I’ve obviously missed something obvious. Can you tell me what it it?
Best wishes
Tony Reynolds (UK)
Hi Tony,
Thanks for dropping by. Have you checked to see whether you’ve added the reference of iTextSharp dll in your project — yeah I understand, its a very basic fault, but I can’t find any other possible reason in my mind right now.
All the best,
Imran Akram
Imran -
Thanks for the suggestion, but I had added the reference.
I’m pleased to say that having worked on it a bit (I told you I was a newbie!) I’ve found the problem. With my version of MS NET or maybe because of some preferences I’ve got, you have to use the full pathname. So now for the failed line I have:-
iTextSharp.text.pdf.PdfWriter.GetInstance(oDoc, new FileStream(”HelloWorld.pdf”, FileMode.Create));
and it works fine.
All the best and please keep up the helpful examples.
Tony Reynolds
Imran,
After looking through a bunch of other html2pdf options, I too finally decided on Supergoos ABCPdf , now I ran into a couple problems..dont know if you have encountered them yet because this only happens when you you are going from a html string (not page) to pdf. When i tried to use relative paths in my src tags, it would either throw an execption, or not display the image. After some looking into the manual and reading some forums, I found out that one of the only options was to use the old outdated? I think BASE tag. If you found a work around for this, please tell me.
Thanks
-Doug
I am working on an asp .net page with updatepanel. I managed to print a pdf file (by merging variable data into the preset field of the template pdf). it doesn’t post back to the page (that I still wants to update the page with the post calculated results). would you please tell me how can I get a post back after sending the page to print?