Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill PDF Form with Itextsharp

I am trying to fill up a form with ITextsharp, and trying out the following code to get all the fields in the pdf:

  string pdfTemplate = @"c:\Temp\questionnaire.pdf";


            PdfReader pdfReader = new PdfReader(pdfTemplate);

            StringBuilder sb = new StringBuilder();
            foreach (var de in pdfReader.AcroFields.Fields)
            {
                sb.Append(de.Key.ToString() + Environment.NewLine);
            }

But the foreach loop is always null count. Do I need to do something to file itself as I have tried the example from here and it works fine... this is an example of pdf I am trying to fill

any ideas?

Edit ::

Null Error on PDF Fields

like image 906
Zaki Avatar asked Jan 24 '13 10:01

Zaki


1 Answers

As it turned out, the PDF "form" to fill in actually wasn't a form (in PDF terms) at all. Thus, your have two choices:

  1. You add the text to the page contents directly using hardcoded or configured "field" positions and dimensions as described by @tschmit007 in comments to his answer.

  2. You add actual PDF form fields to your PDF to generate a true PDF form which you take as template to fill in later.

You can add actual form fields either using some graphical tool allowing that, e.g. Adobe Acrobat, or you can use iText(Sharp). Have a look at chapter 8 of iText in Action — 2nd Edition and the samples available here for Java and here for .Net.

Those samples mostly add form fields to newly generated PDF documents. You can virtually use the same code, though, for adding form fields to a PdfStamper which exposes its inner PdfWriter using stamper.getWriter() in Java and the stamper.Writer in C#. Instead of writer.addAnnotation(field) you have to use stamper.addAnnotation(field, page), though.

like image 120
mkl Avatar answered Sep 18 '22 01:09

mkl