FindTransformed.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 System.Linq;
  9. using GrapeCity.Documents.Common;
  10. using GrapeCity.Documents.Pdf;
  11. using GrapeCity.Documents.Text;
  12.  
  13. namespace DsPdfWeb.Demos
  14. {
  15. // This sample loads the PDF file created by the Transforms sample,
  16. // finds all occurrences of a string in the loaded document,
  17. // and highlights these occurrences. Two points of interest about this sample:
  18. // - The texts in the original document are graphically transformed,
  19. // but the quadrilaterals supplied by the FindText method allows you to easily
  20. // highlight the finds even in that case.
  21. // - The sample inserts a new content stream at index 0 of the page,
  22. // this ensures that the highlighting is drawn UNDER the original content.
  23. // (The same approach may be used to add watermarks etc. to existing files.)
  24. public class FindTransformed
  25. {
  26. public int CreatePDF(Stream stream)
  27. {
  28. // The original file stream must be kept open while working with the loaded PDF,
  29. // see @{LoadPDF} for details:
  30. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Transforms.pdf"));
  31. var doc = new GcPdfDocument();
  32. doc.Load(fs);
  33. // Find all 'Text drawn at', using case-sensitive search:
  34. var finds = doc.FindText(
  35. new FindTextParams("Text drawn at", false, true),
  36. OutputRange.All);
  37.  
  38. // Highlight all finds: first, find all pages where the text was found
  39. var pgIndices = finds.Select(f_ => f_.PageIndex).Distinct();
  40. // Loop through pages, on each page insert a new content stream at index 0,
  41. // so that our highlights go UNDER the original content:
  42. foreach (int pgIdx in pgIndices)
  43. {
  44. var page = doc.Pages[pgIdx];
  45. PageContentStream pcs = page.ContentStreams.Insert(0);
  46. var g = pcs.GetGraphics(page);
  47. foreach (var find in finds.Where(f_ => f_.PageIndex == pgIdx))
  48. {
  49. foreach (var ql in find.Bounds)
  50. {
  51. // Note the solid color used to fill the polygon:
  52. g.FillPolygon(ql, Color.CadetBlue);
  53. g.DrawPolygon(ql, Color.Blue);
  54. }
  55. }
  56. }
  57. // Done:
  58. doc.Save(stream);
  59. return doc.Pages.Count;
  60. }
  61. }
  62. }
  63.