RedactLinks.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.IO;
  6. using System.Drawing;
  7. using System.Text.RegularExpressions;
  8. using System.Collections.Generic;
  9. using GrapeCity.Documents.Pdf;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using GrapeCity.Documents.Pdf.TextMap;
  12. using GrapeCity.Documents.Pdf.AcroForms;
  13. using GrapeCity.Documents.Pdf.Actions;
  14. using GrapeCity.Documents.Common;
  15. using System.Linq;
  16.  
  17. namespace DsPdfWeb.Demos
  18. {
  19. // This sample shows how to find and remove all links to a certain URL from a PDF.
  20. // The code first finds all link annotations with ActionURI pointing to the URL
  21. // that needs to be removed, then uses redact to erase all content within the found link areas.
  22. // Red overlay is used by the redacts to visualize the erased areas.
  23. //
  24. // The PDF used by this sample, but with links intact, can be seen in the FindAndHighlight sample.
  25. public class RedactLinks
  26. {
  27. public int CreatePDF(Stream stream)
  28. {
  29. // Load the PDF with links that need to be remove:
  30. var doc = new GcPdfDocument();
  31. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "fendo-13-1005722.pdf"));
  32. doc.Load(fs);
  33.  
  34. // Remove all links containing this string:
  35. const string targetUrl = "frontiersin.org";
  36.  
  37. // Find all relevant link annotations:
  38. var linkAnnotations = new HashSet<LinkAnnotation>();
  39. foreach (var page in doc.Pages)
  40. {
  41. foreach (var a in page.Annotations)
  42. {
  43. if (a is LinkAnnotation la && la.Action is ActionURI actUri)
  44. {
  45. if (!string.IsNullOrEmpty(actUri.URI) && actUri.URI.Contains(targetUrl))
  46. {
  47. linkAnnotations.Add(la);
  48. }
  49. }
  50. }
  51. }
  52. // Loop through the found links, add redact annotations for each:
  53. foreach (var la in linkAnnotations)
  54. {
  55. foreach (var page in la.Pages)
  56. {
  57. // We must make a copy of page.Annotations to be able to add redact annotations in a foreach loop:
  58. var annots = page.Annotations.Where(a_ => a_ == la).ToList();
  59. foreach (var a in annots)
  60. {
  61. page.Annotations.Add(new RedactAnnotation()
  62. {
  63. Rect = la.Rect,
  64. OverlayFillColor = Color.Red
  65. });
  66. }
  67. }
  68. }
  69. // Apply the redacts:
  70. doc.Redact();
  71.  
  72. // Done:
  73. doc.Save(stream);
  74. return doc.Pages.Count;
  75. }
  76. }
  77. }
  78.