GetImages.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 System.Text;
  9. using GrapeCity.Documents.Pdf;
  10. using GrapeCity.Documents.Text;
  11. using GrapeCity.Documents.Drawing;
  12.  
  13. namespace DsPdfWeb.Demos
  14. {
  15. // This sample loads a PDF (we use the document generated by the Wetlands sample)
  16. // and extracts all images from it. It then prints those images into a new PDF,
  17. // centered one per page.
  18. public class GetImages
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. // Load an existing PDF with some images:
  23. var docSrc = new GcPdfDocument();
  24. using var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands.pdf"));
  25. docSrc.Load(fs);
  26. // This call extracts information about images from the loaded PDF,
  27. // note that for large files it may take a while to complete:
  28. var imageInfos = docSrc.GetImages();
  29.  
  30. var doc = new GcPdfDocument();
  31. var textPt = new PointF(72, 72);
  32. var imageRc = new RectangleF(72, 72 * 2, doc.PageSize.Width - 72 * 2, doc.PageSize.Height - 72 * 3);
  33. var tf = new TextFormat() { Font = StandardFonts.Times, FontSize = 12 };
  34. foreach (var imageInfo in imageInfos)
  35. {
  36. // The same image may appear on multiple locations,
  37. // imageInfo includes page indices and locations on pages;
  38. // for simplicity sake we only print page numbers here:
  39. var sb = new StringBuilder();
  40. imageInfo.Locations.ForEach(il_ => sb.Append((il_.Page.Index + 1).ToString() + ", "));
  41. var g = doc.NewPage().Graphics;
  42. g.DrawString($"This image appears on page(s) {sb.ToString().TrimEnd(' ', ',')} of the original PDF:", tf, new PointF(72, 72));
  43. g.DrawImage(imageInfo.Image, imageRc, null, ImageAlign.ScaleImage);
  44. }
  45. // Done:
  46. doc.Save(stream);
  47. return doc.Pages.Count;
  48. }
  49. }
  50. }
  51.