How to set Read-Only Form Fields based on user in WPF PDF Viewer
The WPF PDF Viewer provides the ability to control form field behavior dynamically based on user-specific information. This functionality enables restricting editing access by setting selected fields to read-only.
Form fields are identified using their assigned names, which act as unique identifiers within the document. Based on these names, form fields can be grouped or organized into user-specific collections. This naming-based grouping approach allows applying different behaviors, such as setting fields to read-only, depending on the associated user.
Steps to set Read-Only Form Fields based on user
Step 1: Create user-based lists from names of form fields
All form fields in the loaded PDF document are iterated and grouped based on their names. Fields that belong to User1 (such as User1_Name, User1_Age, and User1_Country) are added to user1List, while the remaining fields are added to user2List.
This grouping helps organize form fields by user, making it easier to manage them later, such as applying read-only settings or other user-based changes.
private void UpdateFormFields()
{
if (pdfViewer.LoadedDocument.Form != null)
{
var FormFieldCollections = pdfViewer.LoadedDocument.Form.Fields;
if (FormFieldCollections.Count > 0)
{
for (int i = 0; i < FormFieldCollections.Count; i++)
{
if (FormFieldCollections[i].Name == "User1_Name" ||
FormFieldCollections[i].Name == "User1_Age" ||
FormFieldCollections[i].Name == "User1_Country")
{
user1List.Add(FormFieldCollections[i]);
}
else
{
user2List.Add(FormFieldCollections[i]);
}
}
}
}
}
Step 2: Apply Read-Only settings based on user
When the selected user changes (for example, from a ComboBox), the form fields are updated dynamically. Fields of the selected user remain editable, while fields of the other user are set to read-only.
private void UserComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (pdfViewer.LoadedDocument == null) return;
var selectedUser = (UserComboBox.SelectedItem as ComboBoxItem).Content.ToString();
if (selectedUser == "User1")
{
// Enable User1 fields
foreach (var field in user1List)
{
if (field is PdfLoadedTextBoxField textField)
textField.ReadOnly = false;
}
// Set User2 fields as ReadOnly
foreach (var field in user2List)
{
if (field is PdfLoadedTextBoxField textField)
textField.ReadOnly = true;
}
}
else if (selectedUser == "User2")
{
// Enable User2 fields
foreach (var field in user2List)
{
if (field is PdfLoadedTextBoxField textField)
textField.ReadOnly = false;
}
// Set User1 fields as ReadOnly
foreach (var field in user1List)
{
if (field is PdfLoadedTextBoxField textField)
textField.ReadOnly = true;
}
}
}
A complete working sample to hide form fields based on user in a WPF Pdf Viewer Control can be downloaded from GitHub.