StampImage.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.Drawing;
  10. using GrapeCity.Documents.Pdf.Annotations;
  11. using GrapeCity.Documents.Pdf.Graphics;
  12. using System.Numerics;
  13. using GCTEXT = GrapeCity.Documents.Text;
  14. using GCDRAW = GrapeCity.Documents.Drawing;
  15.  
  16. namespace DsPdfWeb.Demos.Basics
  17. {
  18. // This sample demonstrates how to add a custom appearance stream
  19. // to an annotation using a FormXObject.
  20. // We load an existing PDF and then loop over its pages.
  21. // On each page we create a StampAnnotation and a FormXObject
  22. // which is assigned to the annotation's normal default appearance stream.
  23. // A semi-transparent PNG image representing the stamp is then drawn
  24. // on the FormXObject's Graphics using Transform and DrawImage methods.
  25. public class StampImage
  26. {
  27. public int CreatePDF(Stream stream)
  28. {
  29. var doc = new GcPdfDocument();
  30. // Load an existing PDF to which we will add a stamp annotation
  31. // (see LoadPDF for details on loading documents):
  32. var jsFile = Path.Combine("Resources", "PDFs", "The-Rich-History-of-JavaScript.pdf");
  33. using var fs = File.OpenRead(jsFile);
  34. doc.Load(fs);
  35. var rect = new RectangleF(PointF.Empty, doc.Pages[0].Size);
  36. // Create a FormXObject to use as the stamp appearance:
  37. var fxo = new FormXObject(doc, rect);
  38. // Get an image from the resources, and draw it on the FormXObject's graphics
  39. // (see Transformations for details on using GcGraphics.Transform):
  40. using var image = GCDRAW.Image.FromFile(Path.Combine("Resources", "ImagesBis", "draft-copy-450x72.png"));
  41. var center = new Vector2(fxo.Bounds.Width / 2, fxo.Bounds.Height / 2);
  42. fxo.Graphics.Transform =
  43. Matrix3x2.CreateRotation((float)(-55 * Math.PI) / 180f, center) *
  44. Matrix3x2.CreateScale(6, center);
  45. fxo.Graphics.DrawImage(image, fxo.Bounds, null, ImageAlign.CenterImage);
  46. // Loop over pages, add a stamp to each page:
  47. foreach (var page in doc.Pages)
  48. {
  49. // Create a StampAnnotation over the whole page:
  50. var stamp = new StampAnnotation()
  51. {
  52. Icon = StampAnnotationIcon.Draft.ToString(),
  53. Name = "draft",
  54. Page = page,
  55. Rect = rect,
  56. UserName = "Jaime Smith"
  57. };
  58. // Re-use the same FormXObject on all pages:
  59. stamp.AppearanceStreams.Normal.Default = fxo;
  60. }
  61. // Done:
  62. doc.Save(stream);
  63. return doc.Pages.Count;
  64. }
  65. }
  66. }
  67.