如何使用iText7在C#中读取PDF表单的复选框状态?
解决iText7读取PDF复选框选中状态的问题
对于PDF表单中的复选框字段,不能直接用GetValueAsString()获取状态——因为复选框的选中状态并不存储在常规的Value属性里,需要通过专门的复选框字段方法判断。
你需要将获取到的PdfFormField转换为PdfCheckboxFormField类型,再调用IsChecked()方法获取布尔值(对应你表格里的Checked/Selected列数据)。
修改后的代码示例:
using iText; using iText.Kernel.Pdf; using iText.Forms; using iText.Forms.Fields; PdfDocument pdfDoc = new PdfDocument(new PdfReader("file.pdf")); PdfAcroForm form = PdfAcroForm.GetAcroForm(pdfDoc, true); IDictionary<string, PdfFormField> fields = form.GetFormFields(); // 读取Enrolled复选框状态 if (fields.TryGetValue("Enrolled", out PdfFormField enrolledField) && enrolledField is PdfCheckboxFormField enrolledCheckbox) { bool isEnrolledChecked = enrolledCheckbox.IsChecked(); Console.WriteLine($"Enrolled: {isEnrolledChecked}"); // 输出False } // 读取Expired复选框状态 if (fields.TryGetValue("Expired", out PdfFormField expiredField) && expiredField is PdfCheckboxFormField expiredCheckbox) { bool isExpiredChecked = expiredCheckbox.IsChecked(); Console.WriteLine($"Expired: {isExpiredChecked}"); // 输出True } pdfDoc.Close();
补充说明:
IsChecked()方法会自动处理复选框的ExportValue(你的表格里是"On"),直接返回当前是否处于选中状态的布尔值。- 加入类型判断(
enrolledField is PdfCheckboxFormField)是为了避免非复选框字段转换时抛出异常,让代码更健壮。 - 使用完
PdfDocument后记得调用Close()释放资源。
内容的提问来源于stack exchange,提问作者SenatorUppercut
相关产品推荐
相关产品推荐

