7

I'm using LibreOffice 4.1.3.2 to produce a fillable PDF:

  1. Created a Writer document
  2. Set some text and test fields
  3. Exported to PDF

Opening pdf file with Acrobar Reader shows a correct fillable pdf.
Next I use iTextSharp 5.4.5 to fill fields and save flattened document:

var pdf = new PdfReader(srcFilename);
using (var fw = new FileStream(dstFilename, FileMode.Create))
{
    var stamper = new PdfStamper(pdf, fw);
    var f = stamper.AcroFields;

    f.SetField("field1", "John Doe");
    f.SetField("field2", "12/04/2013");
    stamper.FormFlattening = true;
    stamper.Close();
}
pdf.Close();

Problem is that filled fields values completely disappear in new document!
I thought fields were not found or filled, but discovered that commenting stamper.FormFlattening = true field values are there in saved pdf!!
Naturally I need a flattened pdf...

Is there a solution for this?

Marco
  • 56,740
  • 14
  • 129
  • 152

2 Answers2

17

When creating a form using Open Office, Open Office sets a flag telling iText not to create appearances. If you look at the FillDataSheet example, you'll see that we override this with the following line:

fields.setGenerateAppearances(true);

In your specific C# snippet, that would be:

f.GenerateAppearances = true;

It's important to set this value before setting the fields or the appearances won't be created.

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • Thank you, it worked perfectly. Just need to say that `f.GenerateAppearances = true;` must be set before filling fields, or it's useless... – Marco Dec 11 '13 at 18:32
  • f.GenerateAppearances throwing nullreference Exception. Please help – M.S Mar 06 '15 at 09:19
  • 1
    @M.S Please don't "hijack" a correct answer to post an extra question. Create a new question if you have a problem. Also provide the PDF that causes the problem. – Bruno Lowagie Mar 06 '15 at 10:32
  • Thanks Bruno, this saved my hide with a very similar issue like in the question above (customer sending us aweful PDFs made with Scribus). If your other form flattening examples had included this flag/property, I might have gotten there faster ;-) – tom_imk Jun 27 '16 at 07:55
0

It worked with me after adding the following line:

f.SetNeedAppearances(true);
a.karkar
  • 141
  • 1
  • 7
  • You appear to refer to itext 7. The OP and the other answers refer to itext 5. You might want to stress this in your answer. – mkl Feb 20 '21 at 22:07