SearchInLayers.vb
''
'' This code is part of Document Solutions for PDF .NET demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
''
Imports System.IO
Imports System.Drawing
Imports System.Collections.Generic
Imports GrapeCity.Documents.Common
Imports GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Pdf.Layers
Imports GrapeCity.Documents.Pdf.Annotations
Imports GrapeCity.Documents.Pdf.Graphics
Imports GrapeCity.Documents.Text
Imports GrapeCity.Documents.Drawing

Public Class SearchInLayers
    Public Function CreatePDF(ByVal stream As Stream) As Integer
        Using fs = File.OpenRead(Path.Combine("Resources", "PDFs", "lang-layers.pdf"))
            Dim doc = New GcPdfDocument()
            doc.Load(fs)

            Dim regex = "\b(Windows|macOS|Linux|Mac)\b"
            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
        End Using
    End Function

    Private Shared Sub FindInLayer(doc As GcPdfDocument, layer As String, text As String, highlight As Color)
        ' Create a view state with just the specified layer visible:
        Dim 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:
        Dim ftp = New FindTextParams(text, False, False, viewState, 72.0F, 72.0F, True, True)

        ' Find all occurrences of the search text:
        Dim finds = doc.FindText(ftp, OutputRange.All)

        ' Highlight all occurrences on the specified layer only:
        For Each find In finds
            For Each ql In find.Bounds
                Dim g = doc.Pages(find.PageIndex).Graphics
                g.BeginLayer(layer)
                doc.Pages(find.PageIndex).Graphics.FillPolygon(ql, highlight)
                g.EndLayer()
            Next
        Next
    End Sub
End Class