MarkupPerPage.cs
//
// This code is part of GrapeCity Documents for PDF samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Text;
using GrapeCity.Documents.Pdf.Annotations;
using System.Collections.Generic;

namespace GcPdfWeb.Samples
{
    // This example shows how to find all occurrences of two words in a PDF document and
    // underline those occurrences using the text markup underline annotation.
    // This example is similar to FindAndUnderline, but here we create one text markup
    // annotation per page, adding all occurrences of the words to highlight to it,
    // rather than adding a separate annotation for each occurrence.
    public class MarkupPerPage
    {
        public int CreatePDF(Stream stream)
        {
            // Load the PDF:
            var doc = new GcPdfDocument();
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "The-Rich-History-of-JavaScript.pdf"));
            doc.Load(fs);

            // Find all occurrences of "JavaScript" or "ECMAScript" using regex:
            var ft = new FindTextParams("JavaScript|ECMAScript", wholeWord: false, matchCase: false, regex: true);
            var found = doc.FindText(ft, null);

            // Add a text markup annotation per page (keys are page indices):
            Dictionary<int, TextMarkupAnnotation> markups = new Dictionary<int, TextMarkupAnnotation>();
            foreach (var f in found)
            {
                if (!markups.TryGetValue(f.PageIndex, out var markup))
                {
                    markup = new TextMarkupAnnotation()
                    {
                        Page = doc.Pages[f.PageIndex],
                        MarkupType = TextMarkupType.Highlight,
                        Color = Color.Chartreuse
                    };
                    markups[f.PageIndex] = markup;
                }
                foreach (var b in f.Bounds)
                    markup.Area.Add(b);
            }

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