Mahendra Mavani's # Corner

My experiments with software development
posts - 36, comments - 1048, trackbacks - 16

PDF Form Generation using iTextSharp

Forms are one of the very common requirement, especially if you are dealing with any government body. With aspiration towards automation, everybody seems to be moving towards PDF Forms which you can print but doesn't let you save soft copy of it.

On my current project at Headspring, we came across such requirement. System under development deals with multiple organizational bodies. Part of the integration effort needed submitting forms which are in predefined format. Most of the information that needed to be filled in has already been captured by the system. Hence in order to reduce manual work burden and thereby avoiding potential human error (either by typo or due to repeated work burden), it is required to be filled in automatically at the time of generation. In other work, as user to the this system, I want to pick certain record and click on link to generate particular form which is pre-populated with values for current record. Again remember, the original source here is PDF Forms as defined out side the system by third party.

Since open source is heart of our core development effort at Headspring, our first and very natural reaction was to look for any existing open source solution. Our lead architect Kevin Hurwitz has mastery in this area. Given any problem of such nature, Kevin can either elegant open source solution or come up with one, in almost no time (Some day I would like to steal this skill from Kevin).

In this case Kevin has come up with “iTextSharp” library. Little bit experimenting with it here and there, and we concluded that it will meet our requirement perfectly fine. Ours being ASP.NET MVC application, we decided to extend ActionResult which can be hooked up with any application. Here is our approach:

Step one is, ofcourse, download iTextSharp library and take dependency on it. Next is following interface

   1:  public interface IFormBinder<TFormModel>
   2:  {
   3:          byte[] Bind(TFormModel model, string pdfFormTemplateFullPath);
   4:  }

 

This is very simple (generic) interface with just one method. Generic type defined here is Model for any given PDF form [Yes, like all our view page, here to we opted to go with one Model per Form convention.. very soon, we will understand, why]. Next we have abstract implementation for this interface, which will lift most of the burden of filling values to given PDF form. Here is the code for that class:

   1: public abstract class BaseFormBinder<TReportModel> : IFormBinder<TReportModel>
   2:     {
   3:         public virtual void BindFormFields(TReportModel reportModel, AcroFields acroFields) { }
   4:  
   5:         public byte[] Bind(TReportModel reportModel, string pdfTemplateFullPath)
   6:         {
   7:             var memoryStream = new MemoryStream();
   8:  
   9:             PdfStamper pdfStamper = null;
  10:             try
  11:             {
  12:                 var pdfReader = new PdfReader(new RandomAccessFileOrArray(pdfTemplateFullPath), null);
  13:  
  14:                 pdfStamper = new PdfStamper(pdfReader, memoryStream);
  15:  
  16:                 var acroFields = pdfStamper.AcroFields;
  17:  
  18:                 BindFormFields(reportModel, acroFields);
  19:  
  20:                 pdfStamper.FormFlattening = true;
  21:  
  22:                 pdfStamper.Close();
  23:             }
  24:             finally
  25:             {
  26:                 if (pdfStamper != null) pdfStamper.Close();
  27:             }
  28:  
  29:             return memoryStream.ToArray();
  30:         }
  31:     }

This base class reads source PDF form given path and uses iTextSharp library to fill in data to this form and finally returns filled pdf form as byte array.

Next step is creation of custom ActionResult as follow:

   1:  public class PdfFormResult<TFormModel> : ActionResult
   2:      {
   3:          public PdfFormResult(TFormModel model, string formTemplate)
   4:          {
   5:              Model = model;
   6:              FormTemplate = formTemplate;
   7:          }
   8:   
   9:          public TFormModel Model { get; private set; }
  10:          public string FormTemplate { get; set; }
  11:   
  12:   
  13:          public override void ExecuteResult(ControllerContext context)
  14:          {
  15:              var pdfFormTemplateFullPath = HttpContext.Current.Server.MapPath("/PdfForms/" + FormTemplate);
  16:   
  17:              var formBinder = ObjectFactory.GetInstance<IFormBinder<TFormModel>>();
  18:   
  19:              var content = formBinder.Bind(Model, pdfFormTemplateFullPath);
  20:   
  21:              var result = new FileContentResult(content, "binary/octet-stream");
  22:              context.HttpContext.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FormTemplate));
  23:   
  24:              result.ExecuteResult(context);
  25:          }
  26:      }

 

This is yet another generic class, which takes report model as it’s type. Main point worth highlighting here is line 17, which uses IoC container to resolve instance of IFormBinder. To me, this is classic example of leveraging IoC to it’s full capacity and simplifying your code. For my case, IoC is StructureMap and all I have to do to configure it for above need is, define following Structuremap registry: [I defer any further explanation about this to my buddy, Jimmy]

   1:  public class MyRegistry : Registry
   2:      {
   3:          public MyRegistry()
   4:          {
   5:   
   6:              Scan(cfg =>
   7:                       {
   8:                           cfg.Assembly("PdfFormGenerator");
   9:                           cfg.With<DefaultConventionScanner>();
  10:                           cfg.ConnectImplementationsToTypesClosing(typeof(IFormBinder<>));
  11:                       });
  12:          }
  13:      }

 

Once all these in place, for any new pdf form, all I have to do now  is

1) Define Report Model

2) In my controller write action that returns PdfFormResult<ReportModel>

3) Define FormBinder that extends BaseFormBinder<GivenReportModel>  

 

For Completion here is code for all three steps above, for a sample 2 field pdf form

Report Model:

   1:  public class SampleFormModel
   2:      {
   3:          public string Name { get; set; }
   4:          public string Gender { get; set; }
   5:      }

 

Controller Action:

   1:   public PdfFormResult<SampleFormModel> PdfForm()
   2:          {
   3:              var model = UseSomeServiceToGetThisData();
   4:              return new PdfFormResult<SampleFormModel>(model, "SampleForm.pdf");
   5:          }

 

FormBinder:

   1:      public class SampleFormBinder : BaseFormBinder<SampleFormModel>
   2:      {
   3:          public override void BindFormFields(SampleFormModel reportModel, AcroFields acroFields)
   4:          {
   5:              acroFields.SetField("Name", reportModel.Name);
   6:              acroFields.SetField("GenderMale", reportModel.Gender);
   7:              acroFields.SetField("GenderFemale", reportModel.Gender);
   8:          }
   9:      }

 

That’s it. Yes..you are done. Don’t believe me? Here is the sample app, download and play with it yourself .

Till next time…Develop smartly…

Technorati Tags:

Print | posted on Wednesday, February 10, 2010 10:39 PM |

Feedback

Gravatar

# re: PDF Form Generation using iTextSharp

This is the article gives the light in which we can observe the reality. this is very nice one and gives indepth information. thanks soo much for this nice article.
12/16/2010 1:14 AM | online casinos
Gravatar

# re: PDF Form Generation using iTextSharp

This is a long waited concept and every one is desperately waiting for it. Thanks for the review.
1/13/2011 11:49 PM | jeu de casino en ligne
Gravatar

# re: PDF Form Generation using iTextSharp

Thanks for the information a lot
6/14/2011 6:29 AM | resumes
Gravatar

# re: PDF Form Generation using iTextSharp

Don't you recognize that this is high time to get the home loans, which will help you.
7/19/2011 7:28 PM | DEIDRECurry
Gravatar

# re: PDF Form Generation using iTextSharp

It is always good to have a peak of career, however that is complicated to perform premium essays papers. Thence, all that can be real with aid of essay writing service.
8/9/2011 3:28 AM | RoseannStephenson20
Gravatar

# re: PDF Form Generation using iTextSharp

Wow, what a blog! I mean, you just have so much guts to go ahead and tell it like it is. Youre what blogging needs, an open minded superhero who isnt afraid to tell it like it is. This is definitely something people need to be up on. Good luck in the future, man.
8/14/2011 12:11 PM | Acai Berry Diet
Gravatar

# re: PDF Form Generation using iTextSharp

Do you think that nobody can help you with your research papers creating? It's not true, because university essay writing company should give a hand of help every time you require!
8/15/2011 9:57 PM | OdomPaula35
Gravatar

# re: PDF Form Generation using iTextSharp

Fantastic blog! I dont think Ive seen all the angles of this subject the way youve pointed them out. Youre a true star, a rock star man. Youve got so much to say and know so much about the subject that I think you should just teach a class about it...HaHa!
8/17/2011 5:37 AM | Work From Home Mom
Gravatar

# re: PDF Form Generation using iTextSharp

Some guys are modest to buy research paper online. Thus, such guys damage their degrees often. Don't be shy and you would get high results surely.
8/18/2011 5:06 AM | BarryMATTIE20
Gravatar

# re: PDF Form Generation using iTextSharp

I am happy that I learnt something new.
8/18/2011 12:10 PM | Acai Berry Diet
Gravatar

# re: PDF Form Generation using iTextSharp

Different people say that automated articles submission can get more traffic. But, cheap links service can utilize hand operated methods for search engine optimization. Great specialists realize that hand operated methods of SEO.
8/23/2011 9:35 AM | AlbertMattie19
Gravatar

# nike air max 95

Zoo Preferred sateen demand Homepage. Fantastic details you write it very clean.nike air max 90 I am really lucky to get these tips from you, the online are going to be far more beneficial than really prior to.nike air max 2011Can I just say what a relief to uncover somebody who truly knows what theyre talking about on the internet
8/25/2011 2:15 AM | nike air max 95
Gravatar

# re: PDF Form Generation using iTextSharp

Im impressed, I must say. Very rarely do I come across a site thats both informative and entertaining, and let me tell you, youve hit the nail on the head. Your site is important; the issue is something that not enough people are talking intelligently about. Im really happy that I stumbled across this in my search for something relating to this issue.
8/26/2011 11:41 AM | Acai Berry Scam
Gravatar

# re: PDF Form Generation using iTextSharp

To see facts about this good post, we buy a term paper and a href="www.exclusivepapers.com/sitemap.php">cu... writing at the term paper writing services. Lots of essay writing services provide the a href="www.exclusivepapers.com/sitemap.php">essay writing about this post.
8/26/2011 7:59 PM | Combs22Nichole
Gravatar

# re: PDF Form Generation using iTextSharp

What a blog! I mean, you just have so much guts to go ahead and tell it like it is. Youre what blogging needs, an open minded superhero who isnt afraid to tell it like it is. This is definitely something people need to be up on. Good luck in the future, man.
Advantageously, the article is really the best on this notable topic. I harmonize with your conclusions and will thirstily look forward to your approaching updates
8/27/2011 12:19 PM | Acai Berry Scam
Gravatar

# Nice One

This is what I have been searching in many websites and I finally found it here. Amazing article. I am so impressed. Could never think of such a thing is possible with it...I think you have a great knowledge especially while dealings with such subjects.
8/28/2011 7:15 AM | Outcall Tantric Massage
Gravatar

# re: PDF Form Generation using iTextSharp

Wow, what a blog! I mean, you just have so much guts to go ahead and tell it like it is. Youre what blogging needs, an open minded superhero who isnt afraid to tell it like it is. This is definitely something people need to be up on. Good luck in the future, man.
8/30/2011 6:35 AM | Bikeparts & Bike Components
Gravatar

# Nice One

Hey that was great to read. Thanks for the great post .Loved every part of it.
Outstanding blog post, I have marked your site so ideally I’ll see much more on this subject in the foreseeable future.
9/1/2011 2:11 AM | Tantra Massage London
Gravatar

# re: PDF Form Generation using iTextSharp

I just cant stop reading this. Its so cool, so full of information that I just didnt know. Im glad to see that people are actually writing about this issue in such a smart way, showing us all different sides to it. Youre a great blogger. Please keep it up. I cant wait to read whats next.
10/15/2011 11:00 AM | HCG Diet CBS News
Gravatar

# re: PDF Form Generation using iTextSharp

Valuable information and excellent design you got here! I would like to thank you for sharing your thoughts and time into the stuff you post!! Thumbs up
10/22/2011 7:14 AM | HCG Diet
Gravatar

# re: PDF Form Generation using iTextSharp

Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!
10/25/2011 4:42 AM | GNC HCG Diet
Gravatar

# re: PDF Form Generation using iTextSharp

All the information is very good on this website. I will come back to see and speak about all your fascinating articles. All your website is very instructive. I like reading your information. I will come back visiting and commenting in your blog.
10/25/2011 11:07 AM | HCG Diet ABC NEWS
Gravatar

# re: PDF Form Generation using iTextSharp

Your blog is STELLAR! I mean, Ive never been so entertained by anything in my life! Your vids are perfect for this. I mean, how did you manage to find something that matches your style of writing so well? Im really happy I started reading this today. Youve got a follower in me for sure!
10/27/2011 10:21 PM | HCG Diet Plan
Gravatar

# re: PDF Form Generation using iTextSharp

Thank you quite considerably for that complete information.I agree with all the factors pointed out right here and noticed all your essential points. I think it is going to help a lot of people.I used to be little bit conscious about it but your publish gave me distinct thought. thanks
10/28/2011 1:50 PM | HCG Diet
Gravatar

# re: PDF Form Generation using iTextSharp

The family-run establishment serves Northern Italian cuisine in a fine dining atmosphere. Claretta's walls are painted in warm tones, accented by dancing candlelight that makes full wine true religion jeans outlet sparkle like jewels. Service is top-notch, with attention to details such as sweeping the crumbs from the table between courses.
11/3/2011 3:17 AM | cheap true religion jeans
Gravatar

# Amit Ku

I have read many blogs and found good and informatics but this blog has simply thrill me with it designs, colour combination and the most important thing real information. I have found only genuine and useful information on this blog.
11/7/2011 6:01 AM | Cheap Wedding Dresses
Gravatar

# Bridesmaid Dresses

This is one of the highly informatics and attractive blogs that has not only educated also informed me in a very effective manner. There are very few blog like this one I have read.
11/7/2011 6:22 AM | Amit Kumar
Gravatar

# Flowergirl Dresses

Your post have the information that is helpful and very informative. I would like you to keep up the good work.You know how to make your post understandable for most of the people.Thanks for sharing.
11/7/2011 6:35 AM | Amit Kumar
Gravatar

# Womens Canada Goose Expedition Parka

or in walking back and forth between home and school. UGG Knightsbridge Boots 5119 These shoes are so sturdily built that this does not happen. Many times,
11/7/2011 7:48 PM | Womens Canada Goose Expedition P
Gravatar

# re: PDF Form Generation using iTextSharp

Well what can I say? Great post and I totally have the same opinion with you on all points and I am thinking about adding up a link on my blog to your blog post because it’s that good.
11/30/2011 12:11 AM | Professional Cover Letter
Gravatar

# re: PDF Form Generation using iTextSharp

This is a really good post.Beats by Dr Dre

Dr Dre Beats Pro Headphone
Must admit that you are amongst the best bloggers I have read. Thanks for posting this informative article.
12/3/2011 6:34 AM | Beats by Dre Solo HD Headphone
Gravatar

# re: PDF Form Generation using iTextSharp

I put into practice of making use of the internet and I take pleasure in it much and that is the cause why I know about blogging.
12/7/2011 12:36 AM | Professional CV Writers
Gravatar

# watches good

we prefer geting an immitation watch,Armani Watches what's on top of rather of the unaffected fascination in relation to estimate unfeignedly matters. next to our website, the Armani Ceramica Men by are the get the Goa'stter of marginal on perjure yourselfhalf of the big-name snoopes on the subject of noticeable. the bell ross of a top-drawer meet is more than a no-name onjudgeing watch, thus it is innate so as to most populace prerequisite be afterward 114 i Gucci . the petty differences between a real in the midst of a counterfeit watch cannot be noticed commencing a disaffect. K08JDD.persons who cannot afford to buy themselves legal watches had outshine go for the U-Boat Watches considerably which are exclusive, reliable plus bidding impel you constancy exaggerated. A
12/11/2011 11:31 PM | watches good
Gravatar

# re:cheap north face

This is such a wonderful resource that you are providing and you give it cheap oakleys away for free. I love seeing sites that understand the value of providing a north face jackets on sale quality resource for free. It?s the old what goes around comes around routine. My best wishes, I just would like cheap true religion jeans to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon. Pretty cheap oakley sunglasses excellent post. I just stumbled upon your blog site and wished to say that I have really liked reading your site posts. Jodee.
12/12/2011 1:40 AM | cheap north face
Gravatar

# re: PDF Form Generation using iTextSharp

Good work! Your post/article is an excellent example of why I keep approaching back to read your exceptional quality content that is forever updated. Thank you!
12/13/2011 1:49 AM | Cover Letter Writing Services
Gravatar

# Microsoft Office

http://greenspace.ublogg.com/, http://greensoft.e-familyblog.com/, http://microsoftgreen.podbean.com/, http://msofficegreen.soonin.com/, http://www.libraryng.com/blog/20252, http://dosiey.com/pg/blog/officezonegreen, http://biznetsocial.com/pg/blog/officespacegreen, http://officespacegreen.wordpress.com/, http://www.tripdiary.com/softgreen/tripdiary, http://micrgreen.sunteu.ro/, http://imean.com/blog/greenoffice/, http://greenmicrosoft.tradea.org/, http://myindiacafe.com/blogs/greenmsoffice/, http://greenzoneoffice.blogcu.com/, http://greenspace.i.ph/, http://greenmicr.webs.com/apps/blog/, http://officegreen.lovelogger.com/, http://microsoftgreen.monbebeblog.be/, http://connectforfun.com/pg/blog/msofficegreen, http://www.ugether.com/pg/blog/officezonegreen, http://free-wordpress-blog.com/officespacegreen, http://blog.astrakhan.ru/spacegreen/, http://qianbaidu1902.blog.com/, http://panoffice.over-blog.com/, http://officeker.eklablog.com/, http://kermicrosoft.mylivepage.com/blog, http://panmicrosoft.blogdrive.com/, http://ovemicrosoft.beeplog.com/, http://www.free-blog-site.com/ovemsoffice, http://blog.bitcomet.com/16476219/, http://panmsoffice.sweetcircles.com/, http://ovemicroffice.createblog.com/blog/, http://panmicroffice.manablog.jp/, http://microfficeker.blogviaje.com/, http://anyeyouxue.blog.co.nz/, http://www.workingwhilehome.com/zoneker, http://www.worldofwarcraftblogs.com/panzone, http://oveofficespace.blogtur.com/, http://blog.extra.by/kerspace/,

HPWKSFASDGFDF
12/14/2011 2:45 AM | Microsoft Office
Gravatar

# Australia

uggsSheepskin footwear has extended been well-known in the rural places of Australia, and it is recognition enhanced because the remedy was ugg boots discovered by surfers and other people.Sometimes an actress might be observed in UGG Australia Boots, despite the fact that ugg boots outlet there seem to be much more and a lot much more these days.A pair of boots attained some notoriety inside the course on the earth wars when pilots looked for footwear which was warm and comfy on the cold flights in higher uggs clearance altitude. In basic truth, Oprah am fired up through the convenience and warmth of Uggs that she ordered them for her total employees of cheap ugg boots 350 folks. They formulated new designs more than the an extended time, combined with the line now contains slippers, casual footwear, and rather some boot sorts.
12/15/2011 12:33 AM | ugg boots outlet
Gravatar

# re: PDF Form Generation using iTextSharp

Good work! Your post/article is an excellent example of why I keep approaching back to read your exceptional quality content that is forever updated. Thank you!
12/19/2011 6:06 AM | Logo design
Gravatar

# diesel jeans ronhoir

HX-The canada parkas may be within the world of style. diesel jeans uk can help them get out of comfort. However, the australian ugg boots to minimize water http://www.winterboot-sales.com ,consumption of the acquisition, fashion seems to Goose canadian gentleman charm.
12/29/2011 2:41 AM | dieseljeans
Gravatar

# re: PDF Form Generation using iTextSharp

I really enjoyed the way you wrote about this. It is not very often that I encounter such writing and I really just wanted to say that.
1/8/2012 6:35 AM | reverse cell phone lookup
Gravatar

# re: PDF Form Generation using iTextSharp

Nonetheless Kundan thomas sabo uk Sets having modest maang teeka truly are a fantastic choice intended for Festival Jewelry way to.

It also enables the bride and after that the bridesmaids to add their private touch toward th marriage ceremony thomas sabo sale. Immersion wrist watches have an Germa creativit for several year. The corporatio is probably th Geco Observe Business ntains this sort of carries smalle risk within the considerably more substantial business. Immersion wrist watches are created to own got leading quality modern day technology contained in these, which is noticed through every one among th objects. These types of wrist thomas sabo bracelet are currently extremely superior to get a while. The corporatio may be producing wrist watches of this top quality regarding aroun two 10 years, and a lot o of the products are well-known by individuals that rely upon wrist watches regarding accuracy as well as execute within a couple of in the worst type o situations.

The true Immersion Wrist watches have a track record which arrives back on their detect.the beauty of the thomas sabo sale is it happens in numerous shapes and different metals that boost your grace and offer a brand new definition to creat. These types of designs of timepieces are created to thomas sabo jewelry divers the actual required accuracy and also technologies they need every time their distinct lifestyle count on this. A few o the actual Immersion timepieces are presently used in armed services goin while some are setup as leisure bit such as the diving scub timepieces.
1/10/2012 7:16 PM | charms au
Gravatar

# ブランド腕時計

ブランド腕時計 ルイヴィトンコピー ブランドバッグ ブランド腕時計 ルイヴィトンコピー ブランドバッグ ブランド腕時計 ルイヴィトンコピー ブランドバッグ ブランド腕時計 ルイヴィトンコピー ブランドバッグ 1.12 eletronic
1/12/2012 1:37 AM | ブランド腕時計
Gravatar

# re: PDF Form Generation using iTextSharp

Canada Goose Mens gives a macho effect to the men. Possessing a classy leather jackets has become status symbol amongst the Moncler Bags.
1/13/2012 1:46 AM | ski jackets
Gravatar

# re: PDF Form Generation using iTextSharp

But did you've a option, which is specifically essential for young women, brides, expectant wife? You have discovered your special marriage ceremony gown? Check out our bridal store, you can not evening long dress only purchase a wedding ceremony dress, but additionally to choose up all the required gowns to svadeb. Our consultants will make an effort to evening long dress find out what the needs and wishes you present your wedding gown.
1/15/2012 1:45 AM | boxweddingdress
Gravatar

# http://www.winter-boots.biz/

GH-The ugg boots As the winter comes, you’ll understand how barbour jacket is vital and perhaps you opt to shop .
1/18/2012 7:22 PM | barbour wax jacket
Gravatar

# re: PDF Form Generation using iTextSharp

This is a great move,thanks for the good share and keep this blog that updated.
1/27/2012 2:42 PM | loan modification help

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 5 and 1 and type the answer here:

Powered by: