我正在尝试使用 PDFsharp 选中 PDFform 中的复选框。我正在使用下面的代码
PdfCheckBoxField chkbox = (PdfCheckBoxField)(pdf.AcroForm.Fields["chkbox"]);
chk.ReadOnly = false;
chk.Checked = true;
chk.ReadOnly = true;
我在 chk.Checked = true 行上遇到以下错误;
ArgumentNullException 未处理 值不能为空。 参数名称:值
您正在将对象读入“chkbox”,但设置“chk”:
PdfCheckBoxField chkbox = (PdfCheckBoxField)(pdf.AcroForm.Fields["chkbox"]);
chkbox.ReadOnly = false;
chkbox.Checked = true;
chkbox.ReadOnly = true;
我不确定为什么它没有在第一行失败。
这个小宝石来自查看 PDFSharp 源代码。 这是如何设置同名复选框的值。 我无法准确判断这是否是发布的原始问题,但根据错误和我自己的挫败感,我想出了这个解决方案。
//how to handle checking multiple checkboxes with same name
var ck = form.Fields["chkbox"];
if (ck.HasKids)
{
foreach (var item in ck.Fields.Elements.Items) {
//assumes you want to "check" the checkbox. Use "/Off" if you want to uncheck.
//"/Yes" is defined in your pdf document as the checked value. May vary depending on original pdf creator.
((PdfDictionary)(((PdfReference)(item)).Value)).Elements.SetName(PdfAcroField.Keys.V, "/Yes");
((PdfDictionary)(((PdfReference)(item)).Value)).Elements.SetName(PdfAnnotation.Keys.AS, "/Yes");
}
}
else {
((PdfCheckBoxField)(form.Fields["chkbox"])).Checked = true;
}
任何仍然遇到此问题的人,这可能就是您正在寻找的解决方案。在一个复选框上花费了 4 个多小时后,这就是全部工作了。请阅读代码片段中的注释以获取额外说明。
// I'm assuming you already have all the fields in the form
string fqName = "the_fields_name";
PdfAcroField field = fields[fqName];
PdfCheckBoxField cbField;
if ( (cbField = field as PdfCheckBoxField) != null ) {
var chcked = bool.Parse(fieldValues[fqName]); // Whatever logic you have to set the checked/unchecked value goes here
cbField.ReadOnly = false;
cbField.Elements.SetName("/V", chcked ? cbField.Name : cbField.UncheckedName);
cbField.Elements.SetName("/AS", chcked ? cbField.Name : cbField.UncheckedName); // This is what the setter does. I use cbField.Name as in the pdf that's what the checkbox sets when checked(As seen in image). Your PDF you could be able to use cbField.CheckedValue
// cbField.Checked = chcked; // This doesn't work because in Checked's setter the GetNonOffValue() function returns null;
cbField.ReadOnly = true;
}