iText GetTextFromPage返回开始evey页面的文本

时间:2016-03-27 17:23:56

标签: itextsharp

我有这个简单的作品。问题非常奇怪 - 在每次迭代时,读者都会在pdf文档开头后返回整个文本。 可能这很简单,但我看不到它。

...
PdfReader reader = new PdfReader ( path );
PdfReaderContentParser parser = new PdfReaderContentParser ( reader );
...
public void Read(int start, int end)
{
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

    StringBuilder sb = new StringBuilder();

    for (int page = start; page < end; page++)
    {
        try
        {
            sb.Append(PdfTextExtractor.GetTextFromPage(reader, page, strategy));
        }
        catch (Exception ex)
        {
            throw new PdfException(ex.Message, ex.InnerException);
        }

        var p = new Page { Number = page, Content = sb.ToString()};
        sb.Clear();
        PageParsed?.Invoke(this, new PdfEventArgs<Page>(p));
    }
    FileParsed?.Invoke(this, new PdfEventArgs<string>(string.IsNullOrEmpty(Name) ? "File parsed" : Name));
}

1 个答案:

答案 0 :(得分:1)

strategy对象保持状态,因此您必须在循环内移动对象实例化,如下所示:

StringBuilder sb = new StringBuilder();

for (int page = start; page < end; page++)
{
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
    try
    {
        sb.Append(PdfTextExtractor.GetTextFromPage(reader, page, strategy));
    }
    catch (Exception ex)
    {
        throw new PdfException(ex.Message, ex.InnerException);
    }

    var p = new Page { Number = page, Content = sb.ToString()};
    sb.Clear();
    PageParsed?.Invoke(this, new PdfEventArgs<Page>(p));
}

这将解决您的问题。