FindText.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using GrapeCity.Documents.Common;
  9. using GrapeCity.Documents.Pdf;
  10. using GrapeCity.Documents.Text;
  11.  
  12. namespace DsPdfWeb.Demos
  13. {
  14. // This sample loads the PDF file created by the BalancedColumns sample,
  15. // finds all occurrences of the words 'lorem' and 'ipsum' in the loaded document,
  16. // and highlights these two words using different colors.
  17. public class FindText
  18. {
  19. public int CreatePDF(Stream stream)
  20. {
  21. // The original file stream must be kept open while working with the loaded PDF, see LoadPDF for details:
  22. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "BalancedColumns.pdf"));
  23. var doc = new GcPdfDocument();
  24. doc.Load(fs);
  25. // Find all 'lorem', using case-insensitive word search:
  26. var findsLorem = doc.FindText(
  27. new FindTextParams("lorem", true, false),
  28. OutputRange.All);
  29. // Ditto for 'ipsum':
  30. var findsIpsum = doc.FindText(
  31. new FindTextParams("ipsum", true, false),
  32. OutputRange.All);
  33.  
  34. // Highlight all 'lorem' using semi-transparent orange red:
  35. foreach (var find in findsLorem)
  36. foreach (var ql in find.Bounds)
  37. doc.Pages[find.PageIndex].Graphics.FillPolygon(ql, Color.FromArgb(100, Color.OrangeRed));
  38. // Put a violet red border around all 'ipsum':
  39. foreach (var find in findsIpsum)
  40. foreach (var ql in find.Bounds)
  41. doc.Pages[find.PageIndex].Graphics.DrawPolygon(ql, Color.MediumVioletRed);
  42.  
  43. // Done:
  44. doc.Save(stream);
  45. return doc.Pages.Count;
  46. }
  47. }
  48. }
  49.