NubieJ
NubieJ

Reputation: 585

ITextSharp PDFTemplate FormFlattening removes filled data

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.

Upvotes: 8

Views: 13237

Answers (4)

Fábio Gomes
Fábio Gomes

Reputation: 1

In your PDF File, change the property to Visible, the Default value is Visible but not printable.

Upvotes: -2

Daniel Linder
Daniel Linder

Reputation: 24

I found a working solution for this for any och the newer iTextSharp. The way we do it was: 1- Create a copy of the pdf temmplate. 2- populate the copy with data. 3- FormFlatten = true and setFullCompression 4- Combine some of the PDFs to a new document. 5- Move the new combined document and then remove the temp.

This way we got the issue with removed input and if we skipped the "formflatten" it looked ok.

However when we moved the "FormFlatten = true" from step 3 and added it as a seperate step after the moving etc was complete, it worked perfectly.

Hope I explained somewhat ok :)

Upvotes: 0

rhens
rhens

Reputation: 4871

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;

Upvotes: 22

NubieJ
NubieJ

Reputation: 585

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

Upvotes: 3

Related Questions