Search code examples
c#.netpdfpdf-generation

PDF Sharp - AddPages replaces form fields


I have a couple of .pdf pages (they are filled forms) that i want to join into a single pdf file.

First I create a pdf document that will hold the info. Then I'm opening each pdf file,

var docToImport = PdfReader.Open(pathToPdf, PdfDocumentOpenMode.Import);

And adding the first page of each pdf to the document i'm creating

doc.AddPage(docToImport.Pages[0]);

The code, creates the pdf file and appends the pdf files that i want.

The problem that i'm not being able to solve is:

  • if the name of the fields are the same, their values will be overwritten by the next page values.

The last page added, overwrites the previous fields (if they share the same name) Tried changing the field names using

   var form = docIntervencoes.AcroForm;
            var fields = form.Fields;
            var fieldNames = fields.Names;

            for (int idx = 0; idx < fieldNames.Length; ++idx)
            {
                var fieldName = fieldNames[idx];
                var field = fields[fieldName];
                field.Elements.SetName($"/Type {fieldName}", $"/Type {fieldName}_{currentIntNumber}");

            }

currentIntNumber is just an int that is incremented from pdf to pdf to get a different name for the fields.

But is does not change the field names.

I'm pulling my hair over this. Just wanted to add pages to the pdf, and keep them as they are. Without overwriting field values.


Solution

  • Follows the solution to the POSTED issue, using the answer from iPDFdev as a guide:

    • Flatten did not work out. It actually made the fields non editable but they still ended up being overwritten.
    • Rename the fields was the way to go!

    Follows the solution:

    var fields = doc.AcroForm.Fields;
    var fieldNames = fields.Names;
    for (int id = 0; id < fieldNames.Length; ++id){
          var fieldName = fieldNames[id];
          var field = fields[fieldName];
           field.Elements.SetString("/T", $"{ newUniqueFieldName}");
    }
    

    Using the SetString was the way to actually change the field name and not just the dictionay entry.