AdjustCoords.cs
//
// This code is part of Document Solutions for PDF demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using GrapeCity.Documents.Pdf;
using GrapeCity.Documents.Pdf.Annotations;

namespace DsPdfWeb.Demos
{
    // This sample shows how to use the Page.AdjustCoordinates() method
    // to convert visual coordinates (measured from the top left corner
    // of the page according to DsPdf rules) to correct coordinates in a PDF
    // that was loaded into GcPdfDocument and may have arbitrary unknown 
    // transformations applied to its pages. The adjusted coordinates can be
    // used to position annotations (redact in this case) etc.
    //
    // The PDF used in this sample has one page containing the scan of a sample invoice
    // that was rotated 90 degrees clockwise. The PDF page is rotated 270 degrees to
    // compensate (so that visually the page has correct portrait orientation).
    public class AdjustCoords
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            using (var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "invoice-scan-rot270.pdf")))
            {
                doc.Load(fs);

                if (doc.Pages.Count != 1)
                    throw new Exception("Unexpected: sample invoice should have exactly one page.");

                var page = doc.Pages[0];

                // The bounding rectangle of the area to redact,
                // measured from the top left corner of the PDF page.
                // If this rectangle is used as is, it will miss the target content:
                var rectToRedact = new RectangleF(20, 170, 200, 40);

                // The adjusted bounding rectangle, taking into consideration
                // any possible page transformations (rotation in this case):
                var adjusted = page.AdjustCoordinates(rectToRedact);

                // Note: if 'rectToRedact' is used instead of 'adjusted',
                // the redact will miss the target (customer name/address):
                var redact = new RedactAnnotation()
                {
                    Rect = adjusted,
                    OverlayFillColor = Color.Orange,
                    OverlayText = "Redacted",
                    Page = page
                };
                // Apply the redact:
                doc.Redact(redact);

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