NetCore 使用 iTextSharp 读取 PDF 中的文字信息

问题描述:使用默认 iTextSharp 读取文字没有问题,代码如下:

<PackageReference Include="iTextSharp" Version="5.0.5" />
PdfReader reader = new PdfReader(strFileName);
var totalPageCount = reader.NumberOfPages;
for (int i = 0; i < totalPageCount; i++)
{
    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
    string currentText = PdfTextExtractor.GetTextFromPage(reader, i + 1, strategy);
    var tempContent = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
}

但是默认5.X不支持NetCore平台。。。

解决方案:

引用大佬写的新包

<PackageReference Include="iTextSharp.LGPLv2.Core.Fix" Version="1.4.3" />

读取的方法如下:

            PdfReader reader = new PdfReader(strFileName);
            var totalPageCount = reader.NumberOfPages;
            for (int i = 0; i < totalPageCount; i++)
            {
                var streamBytes = reader.GetPageContent(i + 1);
                var tokenizer = new PrTokeniser(new RandomAccessFileOrArray(streamBytes));
                var stringsList = new List<string>();
                while (tokenizer.NextToken())
                {
                    if (tokenizer.TokenType == PrTokeniser.TK_STRING)
                    {
                        stringsList.Add(tokenizer.StringValue);
                    }
                }
                var tempaaa = string.Join("", stringsList);
            }

参考地址:https://github.com/VahidN/iTextSharp.LGPLv2.Core/blob/master/src/iTextSharp.LGPLv2.Core.FunctionalTests/PdfReaderTests.cs

posted @ 2020-05-31 17:31  wangbg  阅读(2653)  评论(1编辑  收藏  举报