PDFsharp & MigraDoc Foundation
https://forum.pdfsharp.net/

Setting Radio Buttons
https://forum.pdfsharp.net/viewtopic.php?f=2&t=4609
Page 1 of 1

Author:  alexw68 [ Thu Jun 20, 2024 4:23 pm ]
Post subject:  Setting Radio Buttons

Hi,

I am running PDFsharp 6.1.0, I am setting the value of Radio buttons with the following code.

PdfAcroField field = acroFormDict.Fields[whatname];
PdfRadioButtonField radioField = field as PdfRadioButtonField;
PDFData data = header.Data.Find(x => x.Name == whatname);
if (data != null && data.Value != null) {
SetOptionByValue(radioField, data.Value.ToString());
}

Which calls

public void SetOptionByValue(PdfRadioButtonField source, string value) {
if (source == null || string.IsNullOrWhiteSpace(value)) return;
if (!value.StartsWith("/", StringComparison.OrdinalIgnoreCase)) value = "/" + value;
List<PdfRadioOption> options = FindOptions(source);
PdfRadioOption selectedOption = options.Find(x => x.Value == value);
if (selectedOption == null) return;
SetOptionByIndex(source, selectedOption.Index);
}

public void SetOptionByIndex(PdfRadioButtonField source, int index) {
if (source == null) return;
List<PdfRadioOption> options = FindOptions(source);
PdfRadioOption selectedOption = options.Find(x => x.Index == index);
if (selectedOption == null) return;
PdfArray kids = (PdfArray)source.Elements["/Kids"];
int j = 0;
foreach (var kid in kids)
{
var kidValues = ((PdfReference)kid).Value as PdfDictionary;
if (j == selectedOption.Index)
kidValues.Elements.SetValue("/AS", new PdfName(selectedOption.Value));
else
kidValues.Elements.SetValue("/AS", new PdfName("/Off"));
j++;
}
}

private List<PdfRadioOption> FindOptions(PdfRadioButtonField source) {
if (source == null) return null;
List<PdfRadioOption> options = [];
PdfArray kids = source.Elements.GetArray("/Kids");
int i = 0;
foreach (var kid in kids)
{
PdfReference kidRef = (PdfReference)kid;
PdfDictionary dict = (PdfDictionary)kidRef.Value;
PdfDictionary dict2 = dict.Elements.GetDictionary("/AP");
PdfDictionary dict3 = dict2.Elements.GetDictionary("/N");
if (dict3.Elements.Keys.Count != 2)
throw new Exception("Option dictionary should only have two values");

foreach (var key in dict3.Elements.Keys)
if (key != "/Off")
{
PdfRadioOption option = new PdfRadioOption() { Index = i, Value = key };
options.Add(option);
}

i++;
}
return options;
}


It looks like it's working, but it's not completely, if I open the modified PDF in Edge/Chrome its set correctly, if I open in FireFox, Safari or Adobe Acrobat Standard it's not set, a few of the online viewers show it set and a few show it unset.

My guess is there is an attribute I am missing that needs to be set correctly.

If I open the PDF in one of the viewers where it does not work, I can set it and it then works, it's just not reading it properly.

Any help would be great.

Thanks for a great library as well.

Alex

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group
https://www.phpbb.com/