首页 > 解决方案 > 如何使用 iTextSharp C# 仅从 PDF 中提取文本字段?

问题描述

我正在尝试从 PDF 文件中提取用户输入表单的数据。该文件由几个基本字段组成,例如名字、姓氏、出生日期等。用户将填写这些字段并发回文档。我只对提取他们输入数据的文本字段感兴趣。这是我到目前为止的代码,它返回 PDF 中的所有数据:

public static string extractedText()
{
    OpenFileDialog dlg = new OpenFileDialog();
    string filepath, text;
    dlg.Filter = "PDF Files(*.PDF)|*.PDF|All Files(*.*)|*.*";
    if (dlg.ShowDialog() == DialogResult.OK)
    {
        filepath = dlg.FileName.ToString();
        string strText = string.Empty;
        try
        {
            PdfReader reader = new PdfReader(filepath);
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                string s = PdfTextExtractor.GetTextFromPage(reader, page, its);
                s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
                strText = strText + s;
                text = strText;
            }
            reader.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return strText;
    } 
    else 
        return "abc";
}

上面的代码成功返回了所有数据,但是,我只需要选择几个字段(文本字段)。如何更具体地了解我正在提取的数据?

标签: c#pdfitext

解决方案


推荐阅读