ITextSharp PDFTemplate FormFlattening removes fill

2019-01-19 05:25发布

问题:

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.

回答1:

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;


回答2:

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



回答3:

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 :)



回答4:

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



标签: c# itextsharp