AnnotationDrawFilter.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.Text;
using GrapeCity.Documents.Pdf.Annotations;
using GrapeCity.Documents.Pdf.Graphics;
using GrapeCity.Documents.Svg;
using GrapeCity.Documents.Drawing;

namespace DsPdfWeb.Demos
{
    // Shows how to programmatically control which annotations to include when saving a PDF as images.
    // The sample loads a one-page PDF containing several annotations, and saves that page as SVG
    // using DrawAnnotationFilter to include only annotations which satisfy certain conditions
    // (free text annotations that are within the page bounds).
    // The SVG is then inserted as the first page of the resulting PDF.
    // The second page shows the original PDF for reference.
    // The PDF used by this sample was generated by AnnotationTypes.
    public class AnnotationDrawFilter
    {
        public int CreatePDF(Stream stream)
        {
            var doc = new GcPdfDocument();
            // Load a PDF with some annotations into the document:
            using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "AnnotationTypes.pdf"));
            doc.Load(fs);
            using var svgStream = new MemoryStream();
            // Draw the first page of the PDF into an SVG:
            doc.Pages[0].SaveAsSvg(svgStream,
                new SaveAsImageOptions()
                {
                    BackColor = Color.Transparent,
                    DrawAnnotationFilter = (GcPdfDocument d, Page p, AnnotationBase a, ref bool draw) =>
                    {
                        // Draw only free text annotations which also fit horizontally within the page bounds:
                        draw = a is FreeTextAnnotation fta && fta.Rect.Left > 0 && fta.Rect.Right < p.Size.Width;
                    }
                });
            svgStream.Position = 0;
            // Create a GcSvgDocument from the saved SVG so that we can draw it in the resulting PDF:
            using var svgDoc = GcSvgDocument.FromStream(svgStream);
            // Insert a page into the PDF and draw the SVG on it, compare to the original on the 2nd page:
            var page = doc.Pages.Insert(0);
            var g = page.Graphics;
            var rc = new RectangleF(36, 36, page.Size.Width - 72, page.Size.Height - 72);
            g.DrawRectangle(rc, Color.DarkGoldenrod);
            g.FillRectangle(rc, Color.PaleGoldenrod);
            g.DrawSvg(svgDoc, rc);

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