前面我们介绍了如何使用Spire.PDF 创建PDF表单域 及 重置表单域字段的值,该文将详细介绍如何使用Spire.PDF读取PDF表单域及获取域里面的值。
读取PDF表单域
C#
//创建PdfDocument实例并加载示例文档
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
//遍历FieldsWidget.List获取所有表单域,并打印出表单域名称
PdfFormWidget formWidget = pdf.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
string fieldName = field.Name;
Console.WriteLine(fieldName);
}
Console.WriteLine("--------------------------------------");
//遍历FieldsWidget.List获取所有表单域,并打印出导出Value为YES的表单域名称
List<PdfField> list = formWidget.FieldsWidget.GetFieldsByExportValue("Yes");
for (int i = 0; i < list.Count; i++)
{
string fieldName = list[i].Name;
Console.WriteLine(fieldName);
}
Console.Read();
VB.NET
'创建PdfDocument实例并加载示例文档
Dim pdf As New PdfDocument()
pdf.LoadFromFile("Sample.pdf")
'遍历FieldsWidget.List获取所有表单域,并打印出表单域名称
Dim formWidget As PdfFormWidget = TryCast(pdf.Form, PdfFormWidget)
For i As Integer = 0 To formWidget.FieldsWidget.List.Count - 1
Dim field As PdfField = TryCast(formWidget.FieldsWidget.List(i), PdfField)
Dim fieldName As String = field.Name
Console.WriteLine(fieldName)
Next
Console.WriteLine("--------------------------------------")
'遍历FieldsWidget.List获取所有表单域,并打印出导出Value为YES的表单域名称
Dim list As List(Of PdfField) = formWidget.FieldsWidget.GetFieldsByExportValue("Yes")
For i As Integer = 0 To list.Count - 1
Dim fieldName As String = list(i).Name
Console.WriteLine(fieldName)
Next
Console.Read()
读取域里面选择的值:
C#
//创建PdfDocument实例并加载示例文档
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Sample.pdf");
//获取PDF文档第一页
PdfPageBase page = pdf.Pages[0];
//遍历FieldsWidget.List获取所有表单域
PdfFormWidget formWidget = pdf.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
//获取单选钮表单域并输出所选择的按钮值
if (field is PdfRadioButtonListFieldWidget)
{
PdfRadioButtonListFieldWidget radioButton = field as PdfRadioButtonListFieldWidget;
foreach (PdfRadioButtonWidgetItem item in radioButton.WidgetItems)
{
if (item.Selected)
{
Console.WriteLine(item.Value);
}
}
}
}
Console.ReadKey();
VB.NET
'创建PdfDocument实例并加载示例文档
Dim pdf As New PdfDocument()
pdf.LoadFromFile("Sample.pdf")
'获取PDF文档第一页
Dim page As PdfPageBase = pdf.Pages(0)
'遍历FieldsWidget.List获取所有表单域
Dim formWidget As PdfFormWidget = TryCast(pdf.Form, PdfFormWidget)
For i As Integer = 0 To formWidget.FieldsWidget.List.Count - 1
Dim field As PdfField = TryCast(formWidget.FieldsWidget.List(i), PdfField)
'获取单选钮表单域并输出所选择的按钮值
If TypeOf field Is PdfRadioButtonListFieldWidget Then
Dim radioButton As PdfRadioButtonListFieldWidget = TryCast(field, PdfRadioButtonListFieldWidget)
For Each item As PdfRadioButtonWidgetItem In radioButton.WidgetItems
If item.Selected Then
Console.WriteLine(item.Value)
End If
Next
End If
Next
Console.ReadKey()