MarkupPerPage.cs
  1. //
  2. // This code is part of Document Solutions for PDF demos.
  3. // Copyright (c) MESCIUS inc. All rights reserved.
  4. //
  5. using System;
  6. using System.IO;
  7. using System.Drawing;
  8. using GrapeCity.Documents.Pdf;
  9. using GrapeCity.Documents.Text;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using System.Collections.Generic;
  12. using GrapeCity.Documents.Common;
  13.  
  14. namespace DsPdfWeb.Demos
  15. {
  16. // This example shows how to find all occurrences of two words in a PDF document and
  17. // underline those occurrences using the text markup underline annotation.
  18. // This example is similar to FindAndUnderline, but here we create one text markup
  19. // annotation per page, adding all occurrences of the words to highlight to it,
  20. // rather than adding a separate annotation for each occurrence.
  21. public class MarkupPerPage
  22. {
  23. public int CreatePDF(Stream stream)
  24. {
  25. // Load the PDF:
  26. var doc = new GcPdfDocument();
  27. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "The-Rich-History-of-JavaScript.pdf"));
  28. doc.Load(fs);
  29.  
  30. // Find all occurrences of "JavaScript" or "ECMAScript" using regex:
  31. var ft = new FindTextParams("JavaScript|ECMAScript", wholeWord: false, matchCase: false, regex: true);
  32. var found = doc.FindText(ft, null);
  33.  
  34. // Add a text markup annotation per page (keys are page indices):
  35. Dictionary<int, Tuple<TextMarkupAnnotation, List<Quadrilateral>>> markups = new Dictionary<int, Tuple<TextMarkupAnnotation, List<Quadrilateral>>>();
  36. foreach (var f in found)
  37. {
  38. if (!markups.TryGetValue(f.PageIndex, out var markup))
  39. {
  40. markup = new Tuple<TextMarkupAnnotation, List<Quadrilateral>>(
  41. new TextMarkupAnnotation()
  42. {
  43. Page = doc.Pages[f.PageIndex],
  44. MarkupType = TextMarkupType.Highlight,
  45. Color = Color.Chartreuse
  46. },
  47. new List<Quadrilateral>());
  48. markups[f.PageIndex] = markup;
  49. }
  50. foreach (var b in f.Bounds)
  51. markup.Item2.Add(b);
  52. }
  53. foreach (var v in markups.Values)
  54. v.Item1.Area = v.Item2;
  55.  
  56. // Done:
  57. doc.Save(stream);
  58. return doc.Pages.Count;
  59. }
  60. }
  61. }
  62.