Tuesday, March 19, 2013

Generate PDF From images using itextsharp

Article is about creating PDF documents using iTextSharp. 

iTextSharp  is a free .NET component, you can download the DLL from http://sourceforge.net/projects/itextsharp/

After downloading the DLL, add reference of DLL in project by clicking on Add Reference from solution explorer.


Namespace :

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;


Code:

            DirectoryInfo dir = new System.IO.DirectoryInfo("Image Path");
            FileInfo[] file;
            file = dir.GetFiles("*.jpg");
            String[] Fname;
            String Path;

 using (FileStream fs = new FileStream(Path+ "Test.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
            {
              
                using (Document doc = new Document())
                {
                    using (PdfWriter writer = PdfWriter.GetInstance(doc, fs))
                    {
                        doc.Open();
                        doc.SetMargins(0, 0, 0, 0);
                       
                        iTextSharp.text.Image importImage;
                       
                        for (int j = 0; j <= file.Length - 1; j++)
                        {
                          
                                Chapter chapter1 = new Chapter("", j);
                                chapter1.NumberDepth = 0;
                                chapter1.TriggerNewPage = true;
                                importImage = iTextSharp.text.Image.GetInstance(file[j].FullName);
                                doc.SetPageSize(new iTextSharp.text.Rectangle(0, 0, importImage.Width, importImage.Height));
                                doc.SetPageSize(new iTextSharp.text.Rectangle(importImage.Width, importImage.Height));
                                chapter1.Add(importImage);
                                doc.Add(chapter1);                          
                           
                        }
                                             
                        doc.Close();
                    }
                }
            }

No comments:

Post a Comment