Find and highlight a word using text markup highlight annotation

PDF TIFF SVG JPG C# VB
FindAndHighlight.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.Pdf;
  9. using GrapeCity.Documents.Text;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using System.Collections.Generic;
  12. using GrapeCity.Documents.Common;
  13.  
  14. namespace DsPdfWeb.Demos
  15. {
  16. // This example shows how to find all occurrences of a word in a PDF document
  17. // and highlight all those occurrences using the text markup highlight annotation.
  18. // This example creates a text markup annotation per occurrence. A different approach
  19. // illustrated in MarkupPerPage is to create a text markup annotation per page.
  20. //
  21. // The PDF used in this example was downloaded from https://www.frontiersin.org/articles/10.3389/fendo.2022.1005722/full.
  22. public class FindAndHighlight
  23. {
  24. public int CreatePDF(Stream stream)
  25. {
  26. // Load the PDF:
  27. var doc = new GcPdfDocument();
  28. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "fendo-13-1005722.pdf"));
  29. doc.Load(fs);
  30.  
  31. // Find all occurrences of the word "childbirths":
  32. var found = doc.FindText(new FindTextParams("childbirths", true, false), null);
  33.  
  34. // Add a text markup annotation to highlight each occurrence:
  35. foreach (var f in found)
  36. {
  37. var markup = new TextMarkupAnnotation()
  38. {
  39. Page = doc.Pages[f.PageIndex],
  40. MarkupType = TextMarkupType.Highlight,
  41. Color = Color.Yellow
  42. };
  43. List<Quadrilateral> area = new List<Quadrilateral>();
  44. foreach (var b in f.Bounds)
  45. area.Add(b);
  46. markup.Area = area;
  47. }
  48.  
  49. // Done:
  50. doc.Save(stream);
  51. return doc.Pages.Count;
  52. }
  53. }
  54. }
  55.