Friday, August 7, 2009

PDF generation using .net

I had got a requirement from client to generate membership certificate as a pdf document for the person who joins the website.We researched and planned to make use a third party library called itextsharpLib.

The requirement was to generate a pdf which had a background image and some text to be placed into the pdf which was not that difficult a requirement and hence was able to finish it off within a day with help from the internet mind you.

The problem with this requirement was that there was very less documentation in the internet about the itextsharp library for .net.

Also we had planned to dynamically generate a web page and convert the HTML to pdf. But there was a lot of complexity in the requirement to generate the pdf using HTML. So, I took the easier route and generated the pdf required pretty easily.

So I refered this link to get the required tutorial needed for my requirement.

Steps I went through to get the requirement done:

  1. Instantiate the memory stream stream, required for holding the pdf document generated.
  2. Create a document object document, with the required page size and other layout options.
  3. Instantiate a PdfWriter object writer, which requires the memory stream and document as parameters.
  4. Open the document object using document.Open() method.
  5. Created the Image element and added it to the document using document.Add(img) where img is the obj of the type Image which would be implemented using the IElement interface. Prior to the adding we needed to have initialized the img properties.
  6. Created a PdfContentbyte object using the line PdfContentByte cb = writer.DirectContent;
  7. Write the content on the image between the lines cb.BeginText(); and cb.EndText(); using the method cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Text to be written", x-coordinate, y-coordinate,z-coordinate);
  8. Close the document object using document.close();
Now that we have the pdf document in the memory stream, putting the document in the HTTPHeader of the existing HTTPContext is pretty simple.
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/pdf";
string test = "document";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+test+".pdf");

And there you are, you will get the pdf document as an attachment in your browser.

P.S: The blog entry is under construction. Will add the code snippet and downloadable source code shortly.

No comments:

Post a Comment