Thursday, January 24, 2013

Filling out PDF forms with iTextSharp

We're looking into ways to help SME's fill out our Dutch Chamber of Commerce forms. These are typically PDF forms and we want to help them out with filling out the form with as much info as possible, to save them the trouble. iTextSharp makes this a breeze ( NuGet site ):
            // Fill out PDF
            PdfReader.unethicalreading = true;          
            var inputFile = new PdfReader("Templates/bv_form.pdf");
            var outputStream = new FileStream("Exports/export.pdf", FileMode.Create, FileAccess.Write);           
            var pdfStamper = new PdfStamper(inputFile, outputStream);

            // Display form field names found in document
            foreach (var field in pdfStamper.AcroFields.Fields)
                var line = string.Format("[{0}]", field.Key);    

            pdfStamper.AcroFields.SetField("1.1", "This value is set by C#");
            pdfStamper.AcroFields.SetField("1.12", "12-12-2012");
            pdfStamper.AcroFields.SetField("3.8", "This value is set by C#");
            pdfStamper.AcroFields.SetField("2.11", "This value is set by C#");
     // close writers and clean up
If an 'owner password' is set on the PDF, you need to set the 'unethicalreading' property to true. There are tools to remove the password from the file, but most also remove the form-fields. Setting checkboxes is a bit tricky - you need to use SetField() and provide the value of the checked box. This is typically "On" or "Off", but in the forms we were using, they used custom values. I found these values by checking the forms, saving the forms and then finding the field values in code. Anyways - good stuff, easy to use, check it out!


  1. This comment has been removed by a blog administrator.

  2. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.