InsertVideo.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.Text;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using DsPdfWeb.Demos.Common;
  12. using System.Xml.Linq;
  13. using System.Linq;
  14.  
  15. namespace DsPdfWeb.Demos.Basics
  16. {
  17. // This demo shows how to replace an image in a PDF with a video clip.
  18. public class InsertVideo
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. var pdfPath = Path.Combine("Resources", "PDFs", "Wetlands.pdf");
  23. var videoPath = Path.Combine("Resources", "Video", "waterfall.mp4");
  24.  
  25. using var fs = File.OpenRead(pdfPath);
  26. var doc = new GcPdfDocument();
  27. doc.Load(fs);
  28. var page = doc.Pages.First();
  29.  
  30. // Find the largest image on the first page:
  31. RectangleF imageRect = RectangleF.Empty;
  32. foreach (var img in page.GetImages())
  33. {
  34. foreach (var l in img.Locations.Where(l_ => l_.Page.Index == 0))
  35. {
  36. var r = l.PageBounds.ToRect();
  37. if (r.Height > imageRect.Height)
  38. imageRect = r;
  39. }
  40. }
  41. if (imageRect == RectangleF.Empty)
  42. throw new Exception("Could not find an image on the first page.");
  43.  
  44. // Remove it:
  45. doc.Redact(new RedactAnnotation() { Page = page, Rect = imageRect });
  46.  
  47. // Add a video clip in the rectangle previously occupied by the image:
  48. var rma = new RichMediaAnnotation();
  49. var videoEfs = EmbeddedFileStream.FromFile(doc, videoPath);
  50. var videoFileSpec = FileSpecification.FromEmbeddedStream(Path.GetFileName(videoPath), videoEfs);
  51. rma.SetVideo(videoFileSpec);
  52. rma.PresentationStyle = RichMediaAnnotationPresentationStyle.Embedded;
  53. rma.ActivationCondition = RichMediaAnnotationActivation.PageBecomesVisible;
  54. rma.DeactivationCondition = RichMediaAnnotationDeactivation.PageBecomesInvisible;
  55. rma.ShowNavigationPane = true;
  56. rma.Page = page;
  57. rma.Rect = imageRect;
  58.  
  59. // Done:
  60. doc.Save(stream);
  61. return doc.Pages.Count;
  62. }
  63. }
  64. }
  65.