AdjustCoords.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.Pdf.Annotations;
  10.  
  11. namespace DsPdfWeb.Demos
  12. {
  13. // This sample shows how to use the Page.AdjustCoordinates() method
  14. // to convert visual coordinates (measured from the top left corner
  15. // of the page according to DsPdf rules) to correct coordinates in a PDF
  16. // that was loaded into GcPdfDocument and may have arbitrary unknown
  17. // transformations applied to its pages. The adjusted coordinates can be
  18. // used to position annotations (redact in this case) etc.
  19. //
  20. // The PDF used in this sample has one page containing the scan of a sample invoice
  21. // that was rotated 90 degrees clockwise. The PDF page is rotated 270 degrees to
  22. // compensate (so that visually the page has correct portrait orientation).
  23. public class AdjustCoords
  24. {
  25. public int CreatePDF(Stream stream)
  26. {
  27. var doc = new GcPdfDocument();
  28. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "invoice-scan-rot270.pdf"));
  29. doc.Load(fs);
  30.  
  31. if (doc.Pages.Count != 1)
  32. throw new Exception("Unexpected: sample invoice should have exactly one page.");
  33.  
  34. var page = doc.Pages[0];
  35.  
  36. // The bounding rectangle of the area to redact,
  37. // measured from the top left corner of the PDF page.
  38. // If this rectangle is used as is, it will miss the target content:
  39. var rectToRedact = new RectangleF(20, 170, 200, 40);
  40.  
  41. // The adjusted bounding rectangle, taking into consideration
  42. // any possible page transformations (rotation in this case):
  43. var adjusted = page.AdjustCoordinates(rectToRedact);
  44.  
  45. // Note: if 'rectToRedact' is used instead of 'adjusted',
  46. // the redact will miss the target (customer name/address):
  47. var redact = new RedactAnnotation()
  48. {
  49. Page = page,
  50. Rect = adjusted,
  51. OverlayFillColor = Color.Orange,
  52. OverlayText = "Redacted",
  53. };
  54. // Apply the redact:
  55. doc.Redact(redact);
  56.  
  57. // Done:
  58. doc.Save(stream);
  59. return doc.Pages.Count;
  60. }
  61. }
  62. }
  63.