FindText.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.Drawing;
using GrapeCity.Documents.Common;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;

namespace DsPdfWeb.Demos
{
    // This sample loads the PDF file created by the BalancedColumns sample,
    // finds all occurrences of the words 'lorem' and 'ipsum' in the loaded document,
    // and highlights these two words using different colors.
    public class FindText
    {
        public int CreatePDF(Stream stream)
        {
            // The original file stream must be kept open while working with the loaded PDF, see LoadPDF for details:
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "BalancedColumns.pdf"));
            var doc = new GcPdfDocument();
            doc.Load(fs);
            // Find all 'lorem', using case-insensitive word search:
            var findsLorem = doc.FindText(
                new FindTextParams("lorem", true, false),
                OutputRange.All);
            // Ditto for 'ipsum':
            var findsIpsum = doc.FindText(
                new FindTextParams("ipsum", true, false),
                OutputRange.All);

            // Highlight all 'lorem' using semi-transparent orange red:
            foreach (var find in findsLorem)
                foreach (var ql in find.Bounds)
                    doc.Pages[find.PageIndex].Graphics.FillPolygon(ql, Color.FromArgb(100, Color.OrangeRed));
            // Put a violet red border around all 'ipsum':
            foreach (var find in findsIpsum)
                foreach (var ql in find.Bounds)
                    doc.Pages[find.PageIndex].Graphics.DrawPolygon(ql, Color.MediumVioletRed);

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