- Get and save information about field values before editing of PDF form.
- Get and compare information about field values when you want to determine changes in PDF form.
Here is C# code snippet that shows how to check whether values of PDF form fields have been changed:
Code: Select all
Dictionary<PdfTreeNodeBase, PdfBasicObject> _fieldValues;
/// <summary>
/// Checks whether values of PDF form fields have been changed.
/// </summary>
public void CheckFieldsAreChanged(PdfDocument document)
{
Dictionary<PdfTreeNodeBase, PdfBasicObject> newFieldValues = GetFieldValues(document);
if (_fieldValues != null)
{
if (AreFieldValuesChanged(_fieldValues, newFieldValues))
MessageBox.Show("Changed");
}
_fieldValues = newFieldValues;
}
/// <summary>
/// Returns a value indicating whether values of PDF form fields have been changed.
/// </summary>
public static bool AreFieldValuesChanged(Dictionary<PdfTreeNodeBase, PdfBasicObject> fieldValues1, Dictionary<PdfTreeNodeBase, PdfBasicObject> fieldValues2)
{
if (fieldValues1.Count != fieldValues2.Count)
return true;
foreach (PdfTreeNodeBase field in fieldValues1.Keys)
{
PdfBasicObject value1 = GetValue(fieldValues1[field]);
if (!fieldValues2.ContainsKey(field))
return true;
PdfBasicObject value2 = GetValue(fieldValues2[field]);
if (value1 == value2)
continue;
if (value1 == null || value2 == null)
return true;
if (value1.ToString() != value2.ToString())
return true;
}
return false;
}
/// <summary>
/// Returns dictionary that contains values of PDF form fields.
/// </summary>
public static Dictionary<PdfTreeNodeBase, PdfBasicObject> GetFieldValues(PdfDocument document)
{
Dictionary<PdfTreeNodeBase, PdfBasicObject> result = new Dictionary<PdfTreeNodeBase, PdfBasicObject>();
if (document.InteractiveForm != null)
{
foreach (PdfInteractiveFormField field in document.InteractiveForm.GetTerminalFields())
{
result.Add(field, ((PdfDictionary)field.BasicObject)["V"]);
}
}
return result;
}
/// <summary>
/// Returns value of PDF form field.
/// </summary>
private static PdfBasicObject GetValue(PdfBasicObject basicObject)
{
if (basicObject is PdfIndirectReference indirectReference)
return PdfIndirectObject.GetByReference(indirectReference).Value;
return basicObject;
}