7

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

4

2 回答 2

5

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();
}
于 2013-01-24T10:25:58.070 回答
5

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.

于 2013-01-24T12:03:35.537 回答