Fill PDF Form with Itextsharp

Zaki picture Zaki · Jan 24, 2013 · Viewed 26.3k times · Source

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

Answer

tschmit007 picture tschmit007 · Jan 24, 2013

try:

using (FileStream outFile = new FileStream("result.pdf", FileMode.Create)) {
    PdfReader pdfReader = new PdfReader("file.pdf");
    PdfStamper pdfStamper = new PdfStamper(pdfReader, outFile);
    AcroFields fields = pdfStamper.AcroFields;
    //rest of the code here
    //fields.SetField("n°1", "value");
    //...
    pdfStamper.Close();
    pdfReader.Close();
}