Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ITextSharp PDFTemplate FormFlattening removes filled data

Tags:

c#

itextsharp

I am porting an existing app from Java to C#. The original app used the IText library to fill PDF form templates and save them as new PDF's. My C# code (example) below:

string templateFilename = @"C:\Templates\test.pdf"; 
string outputFilename = @"C:\Output\demo.pdf";

using (var existingFileStream = new FileStream(templateFilename, FileMode.Open))
{
    using (var newFileStream = new FileStream(outputFilename, FileMode.Create))
    {
        var pdfReader = new PdfReader(existingFileStream);
        var stamper = new PdfStamper(pdfReader, newFileStream);

        var form = stamper.AcroFields;
        var fieldKeys = form.Fields.Keys;

        foreach (string fieldKey in fieldKeys)
        {
            form.SetField(fieldKey, "REPLACED!");
        }

        stamper.FormFlattening = true;
        stamper.Close();
        pdfReader.Close();
    }
}

All works well only if I ommit the

stamper.FormFlattening = true;

line, but then the forms are visible as...forms. When I add the this line, any values set to the form fields are lost, resulting in a blank form. I would really appreciate any advice.

like image 271
NubieJ Avatar asked Sep 20 '13 20:09

NubieJ


2 Answers

Most likely you can resolve this when using iTextSharp 5.4.4 (or later) by forcing iTextSharp to generate appearances for the form fields. In your example code:

var form = stamper.AcroFields;
form.GenerateAppearances = true;
like image 186
rhens Avatar answered Nov 02 '22 18:11

rhens


Resolved the issue by using a previous version of ITextSharp (5.4.3). Not sure what the cause is though...

like image 3
NubieJ Avatar answered Nov 02 '22 16:11

NubieJ