iTextSharp fields rename does not work with Merge

不羁岁月 提交于 2019-12-07 20:16:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!