我有一个有效的解决方案,可以打开PDF文件并获取文本。不幸的是,我需要的值在表单字段中。我尝试了几种获取值的方法,但是我只能获取看起来是表单名称的内容。键值是正确的,但是接收到的值是错误的。
键值返回的公司名称iText.Forms.Fields.PdfTextFormField电话号码iText.Forms.Fields.PdfTextFormField业务联系人数据iText.Forms.Fields.PdfTextFormField名称iText.Forms.Fields.PdfTextFormField
不会返回表单字段中的值。有一个更好的方法吗?
using System;
using System.Collections.Generic;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;
namespace ConsoleApplication1 {
class Class1 {
public string pdfthree(string pdfPath) {
PdfReader reader = new PdfReader(pdfPath);
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false);
IDictionary<string, PdfFormField> Map = new Dictionary<string, PdfFormField>();
Map = acroForm.GetFormFields();
acroForm.GetField("Name");
string output = "";
foreach (String fldName in Map.Keys) {
output += fldName + ": " + Map[fldName].ToString() + "\n";
}
System.IO.File.WriteAllText(pdfPath, output);
document.Close();
reader.Close();
return output;
}
}
}
与其调用PdfFormField#ToString()
,不如调用PdfFormField#GetValueAsString()
来获取字段的值。
完整代码:
using System;
using System.Collections.Generic;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;
namespace ConsoleApplication1 {
class Class1 {
public string pdfthree(string pdfPath) {
PdfReader reader = new PdfReader(pdfPath);
PdfDocument document = new PdfDocument(reader);
PdfAcroForm acroForm = PdfAcroForm.GetAcroForm(document, false);
IDictionary<string, PdfFormField> Map = new Dictionary<string, PdfFormField>();
Map = acroForm.GetFormFields();
acroForm.GetField("Name");
string output = "";
foreach (String fldName in Map.Keys) {
output += fldName + ": " + Map[fldName].GetValueAsString() + "\n";
}
System.IO.File.WriteAllText(pdfPath, output);
document.Close();
reader.Close();
return output;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句