SearchInLayers.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//

using System;
using System.IO;
using System.Linq;
using System.Drawing;
using System.Collections.Generic;
using GrapeCity.Documents.Common;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.Layers;
using GrapeCity.Documents.Pdf.Annotations;
using GrapeCity.Documents.Pdf.Graphics;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Drawing;

namespace DsPdfWeb.Demos
{
    // This example shows how to search for text in certain layers only.
    // The input PDF for this sample was created by LangLayers.
    public class SearchInLayers
    {
        public int CreatePDF(Stream stream)
        {
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "lang-layers.pdf"));
            var doc = new GcPdfDocument();
            doc.Load(fs);

            var regex = "\\b(Windows|macOS|Linux|Mac)\\b";
            // var regex = @"(?=(\W|^))(shoes|shirt|pants)(?!(\W|$))";
            FindInLayer(doc, "English", regex, Color.FromArgb(100, Color.Red));
            FindInLayer(doc, "French", regex, Color.FromArgb(100, Color.Blue));
            FindInLayer(doc, "Russian", regex, Color.FromArgb(100, Color.Green));

            // Save the PDF:
            doc.Save(stream);
            return doc.Pages.Count;
        }

        static void FindInLayer(GcPdfDocument doc, string layer, string text, Color highlight)
        {
            // Create a view state with just the specified layer visible:
            var viewState = new ViewState(doc);
            viewState.SetLayersUIStateExcept(false, layer);
            viewState.SetLayersUIState(true, layer);

            // Create a FindTextParams using our custom view state
            // so that the search is limited to the specified layer only:
            var ftp = new FindTextParams(text, false, false, viewState, 72f, 72f, true, true);

            // Find all occurrences of the search text:
            var finds = doc.FindText(ftp, OutputRange.All);

            // Highlight all occurrences on the specified layer only:
            foreach (var find in finds)
                foreach (var ql in find.Bounds)
                {
                    var g = doc.Pages[find.PageIndex].Graphics;
                    g.BeginLayer(layer);
                    doc.Pages[find.PageIndex].Graphics.FillPolygon(ql, highlight);
                    g.EndLayer();
                }
        }
    }
}