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. var tf = new TextFormat() { Font = StandardFonts.Times, FontSize = 12 };
  23. using (var fs = File.OpenRead(Path.Combine("Resources", "PDFs", "Wetlands.pdf")))
  24. {
  25. var docSrc = new GcPdfDocument();
  26. // Load an existing PDF with some images:
  27. docSrc.Load(fs);
  28. // This call extracts information about images from the loaded PDF,
  29. // note that for large files it may take a while to complete:
  30. var imageInfos = docSrc.GetImages();
  31.  
  32. var doc = new GcPdfDocument();
  33. var textPt = new PointF(72, 72);
  34. var imageRc = new RectangleF(72, 72 * 2, doc.PageSize.Width - 72 * 2, doc.PageSize.Height - 72 * 3);
  35.  
  36. foreach (var imageInfo in imageInfos)
  37. {
  38. // The same image may appear on multiple locations,
  39. // imageInfo includes page indices and locations on pages;
  40. // for simplicity sake we only print page numbers here:
  41. var sb = new StringBuilder();
  42. imageInfo.Locations.ForEach(il_ => sb.Append((il_.Page.Index + 1).ToString() + ", "));
  43. var g = doc.NewPage().Graphics;
  44. g.DrawString($"This image appears on page(s) {sb.ToString().TrimEnd(' ', ',')} of the original PDF:", tf, new PointF(72, 72));
  45. g.DrawImage(imageInfo.Image, imageRc, null, ImageAlign.ScaleImage);
  46. }
  47. // Done:
  48. doc.Save(stream);
  49. return doc.Pages.Count;
  50. }
  51. }
  52. }
  53. }
  54.