Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

c# - 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:Templatesest.pdf"; 
string outputFilename = @"C:Outputdemo.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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...