In SpirePDF version 3.7.0.5040, setting the SelectedIndex property of a RadioButtonList to a value other than -1, saving the file with PdfDocument.SaveToFile, and re-opening the document with PdfDocument.LoadFromFile still shows a SelectedIndex of -1. Strangely, the correct value of SelectedIndex only shows after the PDF file is opened and saved in Acrobat.
Here is the code:
- Code: Select all
// Create a PdfDocument and add a page.
PdfDocument pdf = new PdfDocument();
pdf.Pages.Add();
// Create a radio button list with two buttons.
PdfRadioButtonListField radioButtonList = new PdfRadioButtonListField(pdf.Pages[0], "RadioButtonList");
PdfRadioButtonListItem radioButton1 = new PdfRadioButtonListItem("RadioButton1");
PdfRadioButtonListItem radioButton2 = new PdfRadioButtonListItem("RadioButton2");
radioButton1.Bounds = new RectangleF(20f, 20f, 20f, 20f);
radioButton2.Bounds = new RectangleF(20f, 20f, 20f, 20f);
radioButtonList.Items.Add(radioButton1);
radioButtonList.Items.Add(radioButton2);
pdf.Form.Fields.Add(radioButtonList);
// Assign a SelectedIndex of '1' to the radio button list
// (select the second button).
radioButtonList.SelectedIndex = 1;
// Save the PDF.
pdf.SaveToFile(@"C:\SavedPDF.pdf");
pdf.Dispose();
pdf = null;
// Load the PDF file again (without opening or saving in Acrobat).
pdf = new PdfDocument();
pdf.LoadFromFile(@"C:\SavedPDF.pdf");
// Get the selected index again.
PdfFormWidget formWidget = pdf.Form as PdfFormWidget;
PdfRadioButtonListFieldWidget radioButtonListWidget =
(PdfRadioButtonListFieldWidget)formWidget.FieldsWidget["RadioButtonList"];
int selectedIndex = radioButtonListWidget.SelectedIndex; // shows as -1
A workaround is to save the selected value in a hidden field prior to saving with PdfDocument.SaveToFile:
- Code: Select all
// Store the initial value of the selected index in a hidden field
// before saving.
PdfTextBoxField hiddenField = new PdfTextBoxField(pdf.Pages[0], "InitialValue");
hiddenField.Text = radioButtonList.SelectedIndex.ToString();
hiddenField.Visible = false;
hiddenField.ReadOnly = true;
pdf.Form.Fields.Add(hiddenField);
- Code: Select all
// Return the selected index, or the hidden field value if the selected index
// is -1.
PdfFormWidget formWidget = pdf.Form as PdfFormWidget;
PdfRadioButtonListFieldWidget radioButtonListWidget =
(PdfRadioButtonListFieldWidget)formWidget.FieldsWidget["RadioButtonList"];
PdfTextBoxFieldWidget hiddenFieldWidget = (PdfTextBoxFieldWidget)formWidget.FieldsWidget["InitialValue"];
int selectedIndex = (radioButtonListWidget.SelectedIndex != -1) ?
radioButtonListWidget.SelectedIndex : int.Parse(hiddenFieldWidget.Text);