Uncategorized

Create PDF file using ItextSharp

Sending
User Rating 5 (1 vote)
The .NET framework does not contain any in-built or any support  to work with PDF files. So, if you want to generate or work with PDF files as part of your ASP.NET web application, you will have to rely on one of the many third party components that are available. One of the free components is iTextSharp, which is a part of a well known Java utility.

Since the lack of documentation on Itextsharp.dll using in c#, so it is quite cumbersome for some to work on this. I am putting down here few of my development task i did while working on itextsharp.

One can download the the dll from
http://sourceforge.net/project/platformdownload.php?group_id=72954

Here i will be walk you through how to create
1) Header footer 
2)Adding image file
3)Adding HTML content 
4)Adding Attachment  
to PDF.

Create the class project adding the reference to itextsharp.dll
In the class adding:
 
using iTextSharp.text;
using iTextSharp.text.pdf;

           MemoryStream pdfStream = new MemoryStream();
            var _document = new Document(PageSize.A4, 50, 50, 14, 14);
            PdfWriter _pdfWriter = PdfWriter.GetInstance(_document, pdfStream);
// or instead of pdfStream one can mention the path of the file eg: @"D:\Test\TestPDF.pdf"

Creating header footer in the Pdf file, with page number
 
CreateHeaderFooter(ref  _document);
_document.Open();
 
  public void CreateHeaderFooter(ref Document _document)
        {
 
            var headerfooter = FontFactory.GetFont("Arial", 8, Font.NORMAL);
            HeaderFooter header = (new HeaderFooter(new Phrase("HeaderNote", headerfooter), false));
 
            header.BorderColorTop = new iTextSharp.text.Color(System.Drawing.Color.Red);
            header.BorderWidthTop = 0f;
            _document.Header = header;
 
            HeaderFooter Footer = new HeaderFooter(new Phrase("©2012 FooterNote", headerfooter), true);
            Footer.BorderWidthBottom = 0f;
            _document.Footer = Footer;
        }

 Adding the image file first get the image file in byte array
 
byte[] image = File.ReadAllBytes(@"C:\ Test\Test.png");
 
AddLogo(ref  _document, image);
 
public void AddLogo(ref Document _document, byte[] headerImage)
        {
            var welcomeParagraph = new Paragraph(new Phrase(string.Empty));
            _document.Add(welcomeParagraph);
            var logo = iTextSharp.text.Image.GetInstance(headerImage);
            logo.ScalePercent(40); 
            _document.Add(logo);
        }

Adding HTML Content to PDF file
 


AddHTMLContent( HtmlContent, ref _document);
   public void AddHTMLContent(String HTMLContent, ref Document _document)
        {
            iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
            styles.LoadTagStyle(HtmlTags.ANCHOR, HtmlTags.COLOR, "#0072bc"); // Color to anchor tag
            styles.LoadTagStyle(HtmlTags.TABLE, HtmlTags.BORDERWIDTH, "1");
 
            var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(HTMLContent), styles);
            foreach (var htmlElement in parsedHtmlElements)
                _document.Add(htmlElement as IElement);
        }

Add attachment to the PDF file.
 
CreateHTMLContent( ref _pdfWriter, ref _document);
 
public void CreateHTMLContent(ref PdfWriter _pdfWriter,ref Document _document)
        {
            Dictionary<int, FileDetial> dicFileDetail = new Dictionary<int, FileDetial>();
 
    // Add code to add file detail to dictionary object dicFileDetail.
         
            if (dicFileDetail.Count != 0) // if attachment found then add
            {
                EmptySpaceBefore(ref  _document, 10f);
                // creating the attachment
                Paragraph paraAtachment = new Paragraph();
                Chunk chAttachment = new Chunk("Attachment" + Environment.NewLine, FontFactory.GetFont("Arial", 8, Font.BOLD));
                chAttachment.SetUnderline(0.5f, -1.5f);
                paraAtachment.Add(chAttachment);
 
                foreach (KeyValuePair<int, FileDetial> filedetail in dicFileDetail)
                {
                    // Adding file annotation
                    PdfAnnotation attachment = PdfAnnotation.CreateFileAttachment(_pdfWriter, new Rectangle(1f, 65f, 15f, 7f), "Click to open the file.", File.ReadAllBytes( filedetail.Value.FileHref), null, System.Web.HttpUtility.UrlDecode(filedetail.Value.FileName));
                    attachment.Put(PdfName.NAME, new PdfString("Paperclip"));
 
                    Font lightblue = new Font(Font.COURIER, 8f, Font.NORMAL, new Color(43, 145, 175));
                    Chunk chkFileName = new Chunk("  [" + System.Web.HttpUtility.UrlDecode(filedetail.Value.FileName) + "]", lightblue);
                    //Adding the anotation to chunk
                    Chunk attachLink = new Chunk("\u00a0\u00a0").SetAnnotation(attachment);
 
                    paraAtachment.Add(chkFileName);
                    paraAtachment.Add(attachLink);
                }
                _document.Add(paraAtachment);
            }
 
          
        }

at last
            _pdfWriter.CloseStream = false;
            _document.Close();
            pdfStream.Position = 0;  // set the stream pointer to 0
            //then save the pdf stream object which is an memory stream object as File.
 
FileStream file = new FileStream("file.pdf", FileMode.Create, System.IO.FileAccess.Write);
byte[] bytes = new byte[pdfStream.Length];
pdfStream.Read(bytes, 0, (int)pdfStream.Length);
file.Write(bytes, 0, bytes.Length);
file.Close();
pdfStream.Close();
 

————————————————————————————————————-
If any one looking for the book in "iText in Action" by BRUNO LOWAGIE. please drop me a mail , I will mail you the e-book for the same.

Thanks,
Vimal

Share your Thoughts