Wednesday, November 19, 2014

Step by Step guide to create First PDF report with ADOBE Pro and iTextSharp -- .NET

Recently I had to work on a reporting module for Mobile application. I used iTextSharp to write wrapper class which was responsible for creating PDF files on the fly. The plan was to create PDF forms from Adbobe Acrobat Pro and generate PDF reports using the iTextSharp and my wraper class. My wrapper class takes PDF Template path, Simple Modal object (Just having values to print on PDF) and the output PDF path as input and generate PDF report. Let us see in more detail.

First Install NuGet Package, iTextSharp

Create PDF form 

First create a mock up of a report in the word document,




Open Adobe PDF PRO tool and Choose Create PDF Form,


Choose the Word document that we create in the initial stage,


The generated PDF would look like following,


To Edit the PDF form or see the Name/ID of controls used in PDF form, go into Tools -> Edit

The form would look like following. You can also double click on the control to change the Name/ID of the controls. 
Important! The names highlighted in black are very important. These exact names would be used in .NET code to set the values in PDF.






 Getting our hands dirty with code

Now the first step is to create modal class (with any name) and having properties with names exactly equal (in quantity and name) to the PDF file field names (this requirement is not for iTextSharp, but only for my utility class).


   class ReportModal
   {
       public DateTime Date { getset; }
       public string Name { getset; }
       public DateTime FirstNameRow1 { getset; }
       public DateTime SecondNameRow1 { getset; }
       public DateTime ThirdNameRow1 { getset; }
       public DateTime FourthNameRow1 { getset; }
   }

In the next step, we call our utility by passing the templatepath, outputpath and the actual object. This will generate the PDF report based upon the data provided by the above Modal class object and the PDF template.

static void Main()
       {
           ReportModal reportModal = new ReportModal();
            //Write code for Setting values of reportModal object.
           PDFFormGenerator formGenerator = new PDFFormGenerator(pdfTemplatePathStringpdfGeneratedPathStringreportModal);            formGenerator.Create();                       Console.WriteLine("Done");            Console.ReadLine();        }





Please find the basic utility class that will generate final PDF report. This class has two main methods,


  1. CreateDictionary: This method uses reflection to read all properties of the passed object and make a dictionary object of property name and its value.
  2. CreatePDF: this method uses the dictionary object created in first method and map all the PDF properties with the property values passed in an object.


using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace CreatePDF
{
    public class PDFFormGenerator
    {
        private string InputFilePath { getset; }
 
        private string OutputFilePath { getset; }
 
        private object ObjectToProcess { getset; }
 
        private Dictionary<stringobject> PDFDictionary = new Dictionary<string,object>();
 
        public PDFFormGenerator(string inputFilePath, string outputFilePath, object objectToProcess)
        {
            this.InputFilePath = inputFilePath;
            this.OutputFilePath = outputFilePath;
            this.ObjectToProcess = objectToProcess;
        }
        public void Create()
        {
            CreateDictionary();
            CreatePDF();
        }
        private void CreateDictionary()
        {
 
            
            Type myType = ObjectToProcess.GetType();
            this.PDFDictionary = new Dictionary<stringobject>();
            IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
 
            foreach (PropertyInfo prop in props)
            {
                object propValue = prop.GetValue(ObjectToProcess, null);
                
 
 
                this.PDFDictionary.Add(prop.Name, propValue);
            }
        }
 
        private void CreatePDF()
        {
            PdfReader reader = new PdfReader(InputFilePath);
 
 
            PdfStamper stamper = new PdfStamper(reader, new System.IO.FileStream(OutputFilePath, System.IO.FileMode.Create));
 
            foreach (string key in PDFDictionary.Keys)
            {
                stamper.AcroFields.SetField(key, PDFDictionary[key] + "");
            }
 
 
            stamper.FormFlattening = true;
            stamper.Close();
            reader.Close();
        }
    }
}

No comments:

Post a Comment