我有一个示例 pdf,我正在以编程方式填写它(使用 iText7):-
string name = TextBox1.Text.ToString();
string pdfTemplate = @"..\WebApplication1\Sample.pdf";
string newFile = @"..\WebApplication1\completed_sample.pdf";
PdfDocument pdf = new PdfDocument(new PdfReader(pdfTemplate).SetUnethicalReading(true), new PdfWriter(newFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
// This doesn't work //
fields.TryGetValue("TypeofApplication.1", out toSet);
toSet.SetValue("/On");
// This works //
fields.TryGetValue("FullName", out toSet);
toSet.SetValue(name);
form.FlattenFields();
pdf.Close();
我可以填写 pdf 中的文本框,但不能填写单选按钮/复选框。
应用程序类型在我的 cshtml
页面中有两个选项:
@Html.RadioButton("Application_Type", "New") New
@Html.RadioButton("Application_Type", "Renew") Renewal
当我查看我的值字典时,我发现有 3 个选项:
- 应用程序类型
- 应用程序类型.1
- 应用程序类型.2
如何将复选框设置为 checked = true
。
我的逻辑如下:
if(dr.Application_Type == "New"){
fields.TryGetValue("TypeofApplication.1", out toSet);
toSet.SetValue("/On");}
但这显然行不通。
最佳答案
所以我的解决办法是:-
1) 我打开了 pdf,将复选框设置为选中状态并将其保存在我的工作区文件夹中。
2)然后,我以编程方式打开文件并检查字段值,如下所示:-
string pdfTemplate = @"..\WebApplication1\Sample.pdf";
PdfDocument pdf = new PdfDocument(new PdfReader(pdfTemplate).SetUnethicalReading(true), new PdfWriter(newFile));
PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
IDictionary<String, PdfFormField> fields = form.GetFormFields();
PdfFormField toSet;
fields.TryGetValue("TypeofApplication", out toSet);
var x = toSet.GetValueAsString();
现在,我知道 x 的值,它是选中的字段。 (新的或更新的)。我使用这种技术来查找任何给定复选框、单选按钮列表等的所有可能值。
关于c# - 在 .NET 中使用 iText7 检查 PDF 中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60216299/