c# - 如何从 PDF 中提取所有值?

标签 c# itext7

我有一个可行的解决方案,可以打开 PDF 文件并获取文本。不幸的是,我需要的值在表单字段中。我尝试了几种方法来获取值,但我只能获取看似表单名称的内容。键值是正确的,但接收到的值是错误的。

Key ValueReturned Company Name iText.Forms.Fields.PdfTextFormField Phone Number iText.Forms.Fields.PdfTextFormField Business Contact Data iText.Forms.Fields.PdfTextFormField Name 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#GetValueAsString() 来获取字段的值,而不是调用 PdfFormField#ToString()

完整代码:

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;
        }
    }
}

关于c# - 如何从 PDF 中提取所有值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57731948/

相关文章:

java - 无法在 Java 中使用 iText 7.1.9 创建 PDF

java - itext7 - 如何在 PDF 中绘制水平虚线?

java - 使用 iText 将 SVG 转换为 PDF,SVG 在 PDF 中未完全显示

pdf - 将页码文本添加到 pdf 副本会被 itext 7 翻转/镜像

c# - System.Xml.XPath.XPathException 有一个无效的标记

c# - 为 .NET 数据访问层使用 MySql 存储过程

c# - Xamarin - 找不到类(android 支持库)

c# - ASP.NET Core 本地化 - 不从资源文件返回值,仅返回名称

c# - 在 iText7 (.NET) 中向现有 PDF 的每个页面添加页脚

c# - connection.Close() 和 connection.Dispose() 有什么区别?