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:
- Instantiate the memory stream stream, required for holding the pdf document generated.
- Create a document object document, with the required page size and other layout options.
- Instantiate a PdfWriter object writer, which requires the memory stream and document as parameters.
- Open the document object using document.Open() method.
- 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.
- Created a PdfContentbyte object using the line PdfContentByte cb = writer.DirectContent;
- 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);
- Close the document object using document.close();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/pdf";
string test = "document";
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.