我有一个带有表单的 PDF,其值可以使用 iTextSharp 5.5.11 的 PDFReader.AcroFields.GetField() 方法访问。但我不知道如何迭代字段并打印键和值。我已经尝试过这个问题中提到的方法: How do I enumerate all the fields in a PDF file in ITextSharp
...但没有骰子。我也尝试过使用枚举器:
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using iTextSharp.text;
using iTextSharp.text.pdf;
class DoStuff
{
static void Main(string[] args)
{
string fileName = args[0];
PdfReader reader = new PdfReader(fileName);
AcroFields pdfFormFields = reader.AcroFields;
var enumerator = pdfFormFields.Fields.GetEnumerator();
Console.WriteLine(pdfFormFields.Fields.GetType()); // So it's a 'LinkedDictionary', how do I iterate through that and get keys and values?
while (enumerator.MoveNext()) // Evidently not like this...
{
Console.WriteLine("There are fields in the document, but this never prints");
}
}
}
...但这似乎也不起作用。目前的方法是什么?
最佳答案
你需要这样的东西:
foreach (string key in pdfFormFields.Fields.Keys)
{
// key is the name of the field
}
如果这没有显示任何字段,那么您看到的不是采用 AcroForm 技术的表单,而是一个 XFA 表单,而这样的表单是完全不同的。请参阅How to get a list of the fields in an XFA form?
更新:如果您怀疑该表单是纯 XFA 表单,请尝试以下代码:
XfaForm xfa = pdfFormFields.Xfa;
并检查xfa.XfaPresent
的值。如果为 true
,则您有一个 XFA 表单;如果它是错误的,您可能会遇到损坏的表格。我见过一些表单,其中在页面字典中引用了小部件注释,但在字段数组中没有引用这些小部件注释。曾经有一个工具可以创建这样的破损表格(我忘了是哪个工具)。无论如何:对于人类用户来说,PDF 中看起来好像有交互字段,但对于机器来说,这些都不是真正的字段。请参阅ItextSharp - Acrofields are empty
关于c# - 无法迭代 iTextSharp 中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120214/