问题
This is a follow up to another question I had earlier, after the merge of PDF files with form fields worked successfully, if fields with same names do appear then they are not getting their distinct values from their original documents, it looks like a field with the same name propagate its values to the following fields which have the same name.
This is the code to merge and rename in 2 separate functions:
public byte[] MergeFiles(IList<DBForms> forms)
{
if (forms.Count < 1)
return null;
System.IO.MemoryStream msOutput = new System.IO.MemoryStream();
iTextSharp.text.Document document = new iTextSharp.text.Document();
PdfCopy copy = new PdfCopy(document, msOutput);
copy.SetMergeFields();
document.Open();
List<PdfReader> readers = new List<PdfReader>();
foreach (var docData in forms.Where(d => d.Status != 2))
{
PdfReader reader = new PdfReader(FlattenRenamePdfForm(docData.DocumentFile));
readers.Add(reader);
copy.AddDocument(reader);
}
document.Close();
foreach (PdfReader reader in readers)
{
reader.Close();
}
return msOutput.ToArray();
}
private byte[] FlattenRenamePdfForm(byte[] oldDoc)
{
PdfReader reader = new PdfReader(oldDoc);
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
ICollection<string> keys = stamper.AcroFields.Fields.Keys;
List<string> keysCopy = new List<string>();
foreach (var key in keys)
{
keysCopy.Add(key);
}
foreach (var key in keysCopy)
{
stamper.AcroFields.SetFieldProperty(key, "setfflags", PdfFormField.FF_READ_ONLY, null);
stamper.AcroFields.RenameField(key, String.Format("{0}{1}", key, new Guid()));
}
stamper.Close();
}
reader.Close();
return ms.ToArray();
}
}
This is done when using the latest iTextSharp library, 5.5.10, the test is done on the w8Ben documents
Here are the files
First
Second
Merged
来源:https://stackoverflow.com/questions/44019252/itextsharp-fields-rename-does-not-work-with-merge