ImageTransparency.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.Drawing;
  11. using GCTEXT = GrapeCity.Documents.Text;
  12. using GCDRAW = GrapeCity.Documents.Drawing;
  13.  
  14. namespace DsPdfWeb.Demos
  15. {
  16. // This sample demonstrates the ability of DsPdf to render
  17. // images using a specified transparency (opacity).
  18. public class ImageTransparency
  19. {
  20. public int CreatePDF(Stream stream)
  21. {
  22. var doc = new GcPdfDocument();
  23. var page = doc.NewPage();
  24. var g = page.Graphics;
  25.  
  26. var rc = Common.Util.AddNote(
  27. "GcPdfGraphics.DrawImage() method allows rendering images with a specified opacity. " +
  28. "Below is a random text with an image drawn on top of it using opacity 0.2 (almost transparent), " +
  29. "0.5 (medium transparency) and 1 (non-transparent).",
  30. page);
  31.  
  32. var tl = g.CreateTextLayout();
  33. tl.DefaultFormat.Font = StandardFonts.Times;
  34. tl.DefaultFormat.FontSize = 12;
  35. tl.MaxWidth = page.Size.Width;
  36. tl.MaxHeight = page.Size.Height;
  37. tl.MarginAll = 36;
  38. tl.MarginTop += rc.Bottom;
  39. tl.Append(Common.Util.LoremIpsum(2));
  40. tl.PerformLayout(true);
  41. g.DrawTextLayout(tl, PointF.Empty);
  42.  
  43. using (var image = GCDRAW.Image.FromFile(Path.Combine("Resources", "Images", "puffins.jpg")))
  44. {
  45. var imageRc = new RectangleF(tl.MarginLeft, tl.MarginTop, 144, 144);
  46. // Opacity 0.2:
  47. g.DrawImage(image, imageRc, null, ImageAlign.ScaleImage, 0.2f);
  48. imageRc.Offset(imageRc.Width + 36, 0);
  49. // Opacity 0.5:
  50. g.DrawImage(image, imageRc, null, ImageAlign.ScaleImage, 0.5f);
  51. imageRc.Offset(imageRc.Width + 36, 0);
  52. // Opacity 1 (default):
  53. g.DrawImage(image, imageRc, null, ImageAlign.ScaleImage);
  54.  
  55. // NOTE: we must save document BEFORE disposing the image(s) used in it:
  56. doc.Save(stream);
  57. }
  58. return doc.Pages.Count;
  59. }
  60. }
  61. }
  62.