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);    
                Console.WriteLine(line);           
            }           

            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
            inputFile.Close();
            pdfStamper.Close();     
            outputStream.Close();
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 comment: