SearchInLayers.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5.  
  6. using System;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Drawing;
  10. using System.Collections.Generic;
  11. using GrapeCity.Documents.Common;
  12. using GrapeCity.Documents.Pdf;
  13. using GrapeCity.Documents.Pdf.Layers;
  14. using GrapeCity.Documents.Pdf.Annotations;
  15. using GrapeCity.Documents.Pdf.Graphics;
  16. using GrapeCity.Documents.Text;
  17. using GrapeCity.Documents.Drawing;
  18.  
  19. namespace DsPdfWeb.Demos
  20. {
  21. // This example shows how to search for text in certain layers only.
  22. // The input PDF for this sample was created by LangLayers.
  23. public class SearchInLayers
  24. {
  25. public int CreatePDF(Stream stream)
  26. {
  27. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "lang-layers.pdf"));
  28. var doc = new GcPdfDocument();
  29. doc.Load(fs);
  30.  
  31. var regex = "\\b(Windows|macOS|Linux|Mac)\\b";
  32. // var regex = @"(?=(\W|^))(shoes|shirt|pants)(?!(\W|$))";
  33. FindInLayer(doc, "English", regex, Color.FromArgb(100, Color.Red));
  34. FindInLayer(doc, "French", regex, Color.FromArgb(100, Color.Blue));
  35. FindInLayer(doc, "Russian", regex, Color.FromArgb(100, Color.Green));
  36.  
  37. // Save the PDF:
  38. doc.Save(stream);
  39. return doc.Pages.Count;
  40. }
  41.  
  42. static void FindInLayer(GcPdfDocument doc, string layer, string text, Color highlight)
  43. {
  44. // Create a view state with just the specified layer visible:
  45. var viewState = new ViewState(doc);
  46. viewState.SetLayersUIStateExcept(false, layer);
  47. viewState.SetLayersUIState(true, layer);
  48.  
  49. // Create a FindTextParams using our custom view state
  50. // so that the search is limited to the specified layer only:
  51. var ftp = new FindTextParams(text, false, false, viewState, 72f, 72f, true, true);
  52.  
  53. // Find all occurrences of the search text:
  54. var finds = doc.FindText(ftp, OutputRange.All);
  55.  
  56. // Highlight all occurrences on the specified layer only:
  57. foreach (var find in finds)
  58. foreach (var ql in find.Bounds)
  59. {
  60. var g = doc.Pages[find.PageIndex].Graphics;
  61. g.BeginLayer(layer);
  62. doc.Pages[find.PageIndex].Graphics.FillPolygon(ql, highlight);
  63. g.EndLayer();
  64. }
  65. }
  66. }
  67. }
  68.