'' This code is part of Document Solutions for PDF demos.
'' Copyright (c) MESCIUS inc. All rights reserved.
Imports System.IO
Imports System.Drawing
Imports System.Text
Imports GrapeCity.Documents.Pdf
Imports GrapeCity.Documents.Common
Imports GrapeCity.Documents.Drawing

'' This sample loads the PDF file created by the Transforms sample,
'' finds all occurrences of a string in the loaded document,
'' and highlights these occurrences. Two points of interest about this sample:
'' - The texts in the original document are graphically transformed,
''   but the quadrilaterals supplied by the FindText method allows you to easily
''   highlight the finds even in that case.
'' - The sample inserts a new content stream at index 0 of the page,
''   this ensures that the highlighting is drawn UNDER the original content.
''   (The same approach may be used to add watermarks etc. to existing files.)
Public Class FindTransformed
    Function CreatePDF(ByVal stream As Stream) As Integer
        Dim doc = New GcPdfDocument()
        '' The original file stream must be kept open while working with the loaded PDF, see LoadPDF for details:
        Using fs = New FileStream(Path.Combine("Resources", "PDFs", "Transforms.pdf"), FileMode.Open, FileAccess.Read)
            '' Find all 'Text drawn at', using case-sensitive search:
            Dim finds = doc.FindText(
                New FindTextParams("Text drawn at", False, True),

            '' Highlight all finds: first, find all pages where the text was found
            Dim pgIndices = finds.Select(Function(f_) f_.PageIndex).Distinct()
            '' Loop through pages, on each page insert a new content stream at index 0,
            '' so that our highlights go UNDER the original content:
            For Each pgIdx In pgIndices
                Dim page = doc.Pages(pgIdx)
                Dim pcs = page.ContentStreams.Insert(0)
                Dim g = pcs.GetGraphics(page)
                For Each find In finds.Where(Function(f_) f_.PageIndex = pgIdx)
                    For Each ql In find.Bounds
                        '' Note the solid color used to fill the polygon:
                        g.FillPolygon(ql, Color.CadetBlue)
                        g.DrawPolygon(ql, Color.Blue)
            '' Done:
        End Using
        Return doc.Pages.Count
    End Function
End Class