InsertVideo.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 DsPdfWeb.Demos.Common;
using System.Xml.Linq;
using System.Linq;

namespace DsPdfWeb.Demos.Basics
{
    // This demo shows how to replace an image in a PDF with a video clip.
    public class InsertVideo
    {
        public int CreatePDF(Stream stream)
        {
            var pdfPath = Path.Combine("Resources", "PDFs", "Wetlands.pdf");
            var videoPath = Path.Combine("Resources", "Video", "waterfall.mp4");

            using var fs = File.OpenRead(pdfPath);
            var doc = new GcPdfDocument();
            doc.Load(fs);
            var page = doc.Pages.First();

            // Find the largest image on the first page:
            RectangleF imageRect = RectangleF.Empty;
            foreach (var img in page.GetImages())
            {
                foreach (var l in img.Locations.Where(l_ => l_.Page.Index == 0))
                {
                    var r = l.PageBounds.ToRect();
                    if (r.Height > imageRect.Height)
                        imageRect = r;
                }
            }
            if (imageRect == RectangleF.Empty)
                throw new Exception("Could not find an image on the first page.");

            // Remove it:
            doc.Redact(new RedactAnnotation() { Page = page, Rect = imageRect });

            // Add a video clip in the rectangle previously occupied by the image:
            var rma = new RichMediaAnnotation();
            var videoEfs = EmbeddedFileStream.FromFile(doc, videoPath);
            var videoFileSpec = FileSpecification.FromEmbeddedStream(Path.GetFileName(videoPath), videoEfs);
            rma.SetVideo(videoFileSpec);
            rma.PresentationStyle = RichMediaAnnotationPresentationStyle.Embedded;
            rma.ActivationCondition = RichMediaAnnotationActivation.PageBecomesVisible;
            rma.DeactivationCondition = RichMediaAnnotationDeactivation.PageBecomesInvisible;
            rma.ShowNavigationPane = true;
            rma.Page = page;
            rma.Rect = imageRect;

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