.net 使用iText 7(8.0)测试PDF文件中是否存在字符串

brjng4g3  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(341)

我目前正在做一些基本的基准测试(生成,拆分,合并,读取,压缩)来选择一个C# Pdf库在我的项目中使用。
我正在尝试从PDF文件中提取文本,并检查文本是否包含字符串。该文件是一个生成的发票,具有可利用的文本行,因此可以使用OCR,但不是必要的。
以DYNAMIC PDF为例,文档清晰

  1. PdfDocument inputDocument = new PdfDocument(RessourcesBenchmark.PDF_MERGE_PAGE_TO_APPEND_PATH);
  2. var text = inputDocument.GetText();

字符串
如何在C#中使用iText实现这一点?iText文档做得很奇怪,你要么阅读所有的API,要么阅读他们网站上的电子书或示例,这些总是非常具体的。我找到了this SO article关于注解的信息,并将PDF作为流阅读。
如果有人有一个例子或一个片段来指导我,我已经花了2个小时在这上面。
在我的基准测试之后,我会要求至少将代码发布到github,因为所有这些libraires文档并不总是显而易见的。

camsedfj

camsedfj1#

在André Lemos的帮助下,我找到了一个解决方案。我将在这里发布完整的实现。
在另一篇文章中,我们必须创建一个实现ITextExtractionStrategy接口的自定义类。也许iText中的抽象类可以省去这一步。

  1. //To be able to extract text from our pdf document
  2. public class CustomTextExtractionStrategy : ITextExtractionStrategy
  3. {
  4. private string textResult { get; set; }
  5. public CustomTextExtractionStrategy()
  6. {
  7. }
  8. public void EventOccurred(IEventData data, EventType type)
  9. {
  10. if (type is EventType.RENDER_TEXT)
  11. {
  12. textResult += ((TextRenderInfo)data).GetText();
  13. }
  14. }
  15. public string GetResultantText()
  16. {
  17. return textResult ?? string.Empty;
  18. }
  19. public ICollection<EventType> GetSupportedEvents()
  20. {
  21. return new List<EventType>{
  22. EventType.BEGIN_TEXT,
  23. EventType.RENDER_TEXT,
  24. EventType.END_TEXT,
  25. //EventType.RENDER_IMAGE,
  26. EventType.RENDER_PATH,
  27. EventType.CLIP_PATH_CHANGED };
  28. }
  29. }

字符串
然后,我们可以将此类用作PdfCanvasProcessor中的参数来处理文本,并通过获取CASTED事件来处理

  1. public class ITextBenchmark
  2. {
  3. public ITextBenchmark()
  4. {
  5. }
  6. // Our text extracting method
  7. public IEnumerable<string> TextExtraction()
  8. {
  9. var pdftext = new StringBuilder();
  10. CustomTextExtractionStrategy customTextExtractionStrategy = new CustomTextExtractionStrategy();
  11. PdfDocument pdfDocument = new PdfDocument(new PdfReader(RessourcesBenchmark.PDF_MERGE_PAGE_TO_APPEND_PATH));
  12. PdfCanvasProcessor parser = new PdfCanvasProcessor(customTextExtractionStrategy);
  13. //Process all the pages of the document
  14. for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++)
  15. {
  16. parser.ProcessPageContent(pdfDocument.GetPage(i));
  17. // Here we have to extract data from the event listener contained in the parser.
  18. var eventResult = (CustomTextExtractionStrategy)parser.GetEventListener();
  19. pdftext.Append(eventResult.GetResultantText());
  20. parser.Reset();
  21. }
  22. if (pdftext.ToString().Contains("*"))
  23. {
  24. return new List<string> { $"The pdf contains '*'" };
  25. }
  26. else
  27. {
  28. return new List<string> { "Unavailable" };
  29. }
  30. }
  31. }

展开查看全部
odopli94

odopli942#

有一种方法可以使用C# * 从PDF中检索文本,而不需要 * 使用自定义文本提取策略。使用NET Core很简单,只需要itext7 nuget包。(可以在here中找到工作解决方案的链接)。

  1. using iText.Kernel.Pdf;
  2. using iText.Kernel.Pdf.Canvas.Parser;
  3. using iText.Kernel.Pdf.Canvas.Parser.Listener;
  4. namespace ScanTextInPDFs
  5. {
  6. internal class Program
  7. {
  8. public static async Task Main(string[] args)
  9. {
  10. string executingDirectory = AppContext.BaseDirectory;
  11. byte[] bytes = await File.ReadAllBytesAsync($"{executingDirectory}PDFs\\Brochure.pdf");
  12. string textToFind = "Lorem ipsum";
  13. bool foundText = false;
  14. using (MemoryStream memoryStream = new MemoryStream(bytes))
  15. {
  16. using PdfReader pdfReader = new PdfReader(memoryStream);
  17. using PdfDocument pdfDocument = new PdfDocument(pdfReader);
  18. for (int page = 1; page <= pdfDocument.GetNumberOfPages(); page++)
  19. {
  20. PdfPage pdfPage = pdfDocument.GetPage(page);
  21. string pageText = PdfTextExtractor.GetTextFromPage(pdfPage, new SimpleTextExtractionStrategy());
  22. if (pageText.Contains(textToFind, StringComparison.Ordinal))
  23. foundText = true;
  24. }
  25. }
  26. if (foundText)
  27. Console.WriteLine($"Found '{textToFind}' in the pdf.");
  28. else
  29. Console.WriteLine($"Did not find '{textToFind}' in the pdf.");
  30. }
  31. }
  32. }

字符串

展开查看全部

相关问题