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. 🙂

Advertisements

Author: Imran Akram

A .NET/SharePoint Consultant and a political enthusiast who believes in putting the feet of the elected and/or unelected officials to fire in order to get good governance.

16 thoughts on “Generating PDF document in .NET using iTextSharp Library”

  1. 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)

  2. 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

  3. 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

  4. 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

  5. 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?

  6. Hye Imran

    I got the error on this line when i convert html string to pdf

    HtmlParser.Parse(document, _xmlr);

    Error:The document is not open yet; you can only add Meta information.

    You have any idea about that.

  7. hi imran this is manoj i also using iTextsharp.dll for creating document but i am unable add Line-height in document and can not parse the tags also please help me

  8. hi,

    I am using itextsharp to create a pdf.
    i create a pdf and fetched sales data by using a sql query.
    data is : bill date bill no bill amount.
    it is 1000 rows.
    i want a page total of bill amount for every page.
    page size is a4.
    how do i measure that this is the end of page and i have to print my total.

  9. Hi,

    I´m trying ABCPdf too, but I´m getting troubles when I try to change the default page size from the document, do you know to do this ?
    I need use paper size A4

    Thanks

      1. the interesting case here is that
        The link interface I made is not a common link, instead it is a ButtonField that appeared as Link inside DataGrid…

        and somehow, I just realized it last night that… the ButtonField that appeared as Link would eventually call as Javascript call not a direct call. Thus, that’s why my VB.net code behind didn’t give me the PDF output, instead it streamed into the Javascript calls….

        If there’s somebody could give me a hint…
        Discussed Here.

      2. I think you can try using a link button instead with a Click event handler. You can assign the ID (or something) that you’re using to pull the data to generate the pdf, to the CommandArgument property. In that click event handler, you need to cast the Object parameter to LinkButton and then get the corresponding CommandArgument Property of that. This should work, I’m pretty sure of that.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s